blob: 63d6fa3b783d80764f6e46de9d4e64ffbc65da2c [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;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070065import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070066import android.content.IIntentReceiver;
67import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070068import android.content.Intent;
69import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070070import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.content.pm.ActivityInfo;
72import android.content.pm.ApplicationInfo;
73import android.content.pm.ConfigurationInfo;
74import android.content.pm.IPackageDataObserver;
75import android.content.pm.IPackageManager;
76import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080077import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.content.pm.PackageManager;
Adam Powelldd8fab22012-03-22 17:47:27 -070079import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070080import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.content.pm.ProviderInfo;
82import android.content.pm.ResolveInfo;
83import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070084import android.content.pm.UserInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040085import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.content.res.Configuration;
87import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070088import android.net.Proxy;
89import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.net.Uri;
91import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080092import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080093import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070094import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080095import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080097import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.FileUtils;
99import android.os.Handler;
100import android.os.IBinder;
101import android.os.IPermissionController;
102import android.os.Looper;
103import android.os.Message;
104import android.os.Parcel;
105import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700107import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.os.RemoteException;
109import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700110import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import android.os.SystemClock;
112import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700113import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700115import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800117import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700118import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700120import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700122import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700123import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.view.Gravity;
125import android.view.LayoutInflater;
126import android.view.View;
127import android.view.WindowManager;
128import android.view.WindowManagerPolicy;
129
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700130import java.io.BufferedInputStream;
131import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700132import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700133import java.io.DataInputStream;
134import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.File;
136import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700137import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700139import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200140import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800141import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700143import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.lang.ref.WeakReference;
145import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700146import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700147import java.util.Collections;
148import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149import java.util.HashMap;
150import java.util.HashSet;
151import java.util.Iterator;
152import java.util.List;
153import java.util.Locale;
154import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700155import java.util.Map.Entry;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700156import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700157import java.util.concurrent.atomic.AtomicBoolean;
158import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700160public final class ActivityManagerService extends ActivityManagerNative
161 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700162 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700164 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400166 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 static final boolean DEBUG_SWITCH = localLOGV || false;
168 static final boolean DEBUG_TASKS = localLOGV || false;
169 static final boolean DEBUG_PAUSE = localLOGV || false;
170 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
171 static final boolean DEBUG_TRANSITION = localLOGV || false;
172 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800173 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700174 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700176 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 static final boolean DEBUG_VISBILITY = localLOGV || false;
178 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700179 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700180 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800181 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700183 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700184 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700185 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700186 static final boolean DEBUG_POWER = localLOGV || false;
187 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700188 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 static final boolean VALIDATE_TOKENS = false;
190 static final boolean SHOW_ACTIVITY_START_TIME = true;
191
192 // Control over CPU and battery monitoring.
193 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
194 static final boolean MONITOR_CPU_USAGE = true;
195 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
196 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
197 static final boolean MONITOR_THREAD_CPU_USAGE = false;
198
Dianne Hackborn1655be42009-05-08 14:29:01 -0700199 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700200 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700201
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800202 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700204 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 // Maximum number of recent tasks that we can remember.
207 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700208
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700209 // Amount of time after a call to stopAppSwitches() during which we will
210 // prevent further untrusted switches from happening.
211 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
213 // How long we wait for a launched process to attach to the activity manager
214 // before we decide it's never going to come up for real.
215 static final int PROC_START_TIMEOUT = 10*1000;
216
Jeff Brown3f9dd282011-07-08 20:02:19 -0700217 // How long we wait for a launched process to attach to the activity manager
218 // before we decide it's never going to come up for real, when the process was
219 // started with a wrapper for instrumentation (such as Valgrind) because it
220 // could take much longer than usual.
221 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 // How long to wait after going idle before forcing apps to GC.
224 static final int GC_TIMEOUT = 5*1000;
225
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700226 // The minimum amount of time between successive GC requests for a process.
227 static final int GC_MIN_INTERVAL = 60*1000;
228
Dianne Hackborn287952c2010-09-22 22:34:31 -0700229 // The rate at which we check for apps using excessive power -- 15 mins.
230 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
231
232 // The minimum sample duration we will allow before deciding we have
233 // enough data on wake locks to start killing things.
234 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
235
236 // The minimum sample duration we will allow before deciding we have
237 // enough data on CPU usage to start killing things.
238 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800241 static final int BROADCAST_FG_TIMEOUT = 10*1000;
242 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
244 // How long we wait for a service to finish executing.
245 static final int SERVICE_TIMEOUT = 20*1000;
246
247 // How long a service needs to be running until restarting its process
248 // is no longer considered to be a relaunch of the service.
249 static final int SERVICE_RESTART_DURATION = 5*1000;
250
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700251 // How long a service needs to be running until it will start back at
252 // SERVICE_RESTART_DURATION after being killed.
253 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
254
255 // Multiplying factor to increase restart duration time by, for each time
256 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
257 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
258
259 // The minimum amount of time between restarting services that we allow.
260 // That is, when multiple services are restarting, we won't allow each
261 // to restart less than this amount of time from the last one.
262 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 // Maximum amount of time for there to be no activity on a service before
265 // we consider it non-essential and allow its process to go on the
266 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700267 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268
269 // How long we wait until we timeout on key dispatching.
270 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 // How long we wait until we timeout on key dispatching during instrumentation.
273 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
274
Dan Egnor42471dd2010-01-07 17:25:22 -0800275 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276
277 static final String[] EMPTY_STRING_ARRAY = new String[0];
278
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700279 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700280
281 private final boolean mHeadless;
282
Joe Onorato54a4a412011-11-02 20:50:08 -0700283 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
284 // default actuion automatically. Important for devices without direct input
285 // devices.
286 private boolean mShowDialogs = true;
287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700289 * Description of a request to start a new activity, which has been held
290 * due to app switches being disabled.
291 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700292 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700293 ActivityRecord r;
294 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700295 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700296 }
297
298 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
299 = new ArrayList<PendingActivityLaunch>();
300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800302 BroadcastQueue mFgBroadcastQueue;
303 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800304 // Convenient for easy iteration over the queues. Foreground is first
305 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800306 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800307
308 BroadcastQueue broadcastQueueForIntent(Intent intent) {
309 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
310 if (DEBUG_BACKGROUND_BROADCAST) {
311 Slog.i(TAG, "Broadcast intent " + intent + " on "
312 + (isFg ? "foreground" : "background")
313 + " queue");
314 }
315 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
316 }
317
318 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
319 for (BroadcastQueue queue : mBroadcastQueues) {
320 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
321 if (r != null) {
322 return r;
323 }
324 }
325 return null;
326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327
328 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 * Activity we have told the window manager to have key focus.
330 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700331 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700332 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 * List of intents that were used to start the most recent tasks.
334 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700335 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336
337 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700338 * Process management.
339 */
340 final ProcessList mProcessList = new ProcessList();
341
342 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 * All of the applications we currently have running organized by name.
344 * The keys are strings of the application package name (as
345 * returned by the package manager), and the keys are ApplicationRecord
346 * objects.
347 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700348 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349
350 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800351 * The currently running isolated processes.
352 */
353 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
354
355 /**
356 * Counter for assigning isolated process uids, to avoid frequently reusing the
357 * same ones.
358 */
359 int mNextIsolatedProcessUid = 0;
360
361 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700362 * The currently running heavy-weight process, if any.
363 */
364 ProcessRecord mHeavyWeightProcess = null;
365
366 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 * The last time that various processes have crashed.
368 */
369 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
370
371 /**
372 * Set of applications that we consider to be bad, and will reject
373 * incoming broadcasts from (which the user has no control over).
374 * Processes are added to this set when they have crashed twice within
375 * a minimum amount of time; they are removed from it when they are
376 * later restarted (hopefully due to some user action). The value is the
377 * time it was added to the list.
378 */
379 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
380
381 /**
382 * All of the processes we currently have running organized by pid.
383 * The keys are the pid running the application.
384 *
385 * <p>NOTE: This object is protected by its own lock, NOT the global
386 * activity manager lock!
387 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700388 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389
390 /**
391 * All of the processes that have been forced to be foreground. The key
392 * is the pid of the caller who requested it (we hold a death
393 * link on it).
394 */
395 abstract class ForegroundToken implements IBinder.DeathRecipient {
396 int pid;
397 IBinder token;
398 }
399 final SparseArray<ForegroundToken> mForegroundProcesses
400 = new SparseArray<ForegroundToken>();
401
402 /**
403 * List of records for processes that someone had tried to start before the
404 * system was ready. We don't start them at that point, but ensure they
405 * are started by the time booting is complete.
406 */
407 final ArrayList<ProcessRecord> mProcessesOnHold
408 = new ArrayList<ProcessRecord>();
409
410 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 * List of persistent applications that are in the process
412 * of being started.
413 */
414 final ArrayList<ProcessRecord> mPersistentStartingProcesses
415 = new ArrayList<ProcessRecord>();
416
417 /**
418 * Processes that are being forcibly torn down.
419 */
420 final ArrayList<ProcessRecord> mRemovedProcesses
421 = new ArrayList<ProcessRecord>();
422
423 /**
424 * List of running applications, sorted by recent usage.
425 * The first entry in the list is the least recently used.
426 * It contains ApplicationRecord objects. This list does NOT include
427 * any persistent application records (since we never want to exit them).
428 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800429 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 = new ArrayList<ProcessRecord>();
431
432 /**
433 * List of processes that should gc as soon as things are idle.
434 */
435 final ArrayList<ProcessRecord> mProcessesToGc
436 = new ArrayList<ProcessRecord>();
437
438 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800439 * This is the process holding what we currently consider to be
440 * the "home" activity.
441 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700442 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800443
444 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700445 * This is the process holding the activity the user last visited that
446 * is in a different process from the one they are currently in.
447 */
448 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800449
450 /**
451 * The time at which the previous process was last visible.
452 */
453 long mPreviousProcessVisibleTime;
454
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700455 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400456 * Packages that the user has asked to have run in screen size
457 * compatibility mode instead of filling the screen.
458 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700459 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400460
461 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 * Set of PendingResultRecord objects that are currently active.
463 */
464 final HashSet mPendingResultRecords = new HashSet();
465
466 /**
467 * Set of IntentSenderRecord objects that are currently active.
468 */
469 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
470 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
471
472 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800473 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700474 * already logged DropBox entries for. Guarded by itself. If
475 * something (rogue user app) forces this over
476 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
477 */
478 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
479 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
480
481 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700482 * Strict Mode background batched logging state.
483 *
484 * The string buffer is guarded by itself, and its lock is also
485 * used to determine if another batched write is already
486 * in-flight.
487 */
488 private final StringBuilder mStrictModeBuffer = new StringBuilder();
489
490 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 * Keeps track of all IIntentReceivers that have been registered for
492 * broadcasts. Hash keys are the receiver IBinder, hash value is
493 * a ReceiverList.
494 */
495 final HashMap mRegisteredReceivers = new HashMap();
496
497 /**
498 * Resolver for broadcast intents to registered receivers.
499 * Holds BroadcastFilter (subclass of IntentFilter).
500 */
501 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
502 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
503 @Override
504 protected boolean allowFilterResult(
505 BroadcastFilter filter, List<BroadcastFilter> dest) {
506 IBinder target = filter.receiverList.receiver.asBinder();
507 for (int i=dest.size()-1; i>=0; i--) {
508 if (dest.get(i).receiverList.receiver.asBinder() == target) {
509 return false;
510 }
511 }
512 return true;
513 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700514
515 @Override
516 protected String packageForFilter(BroadcastFilter filter) {
517 return filter.packageName;
518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 };
520
521 /**
522 * State of all active sticky broadcasts. Keys are the action of the
523 * sticky Intent, values are an ArrayList of all broadcasted intents with
524 * that action (which should usually be one).
525 */
526 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
527 new HashMap<String, ArrayList<Intent>>();
528
Amith Yamasani742a6712011-05-04 14:49:28 -0700529 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530
531 /**
532 * All currently bound service connections. Keys are the IBinder of
533 * the client's IServiceConnection.
534 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700535 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
536 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537
538 /**
539 * List of services that we have been asked to start,
540 * but haven't yet been able to. It is used to hold start requests
541 * while waiting for their corresponding application thread to get
542 * going.
543 */
544 final ArrayList<ServiceRecord> mPendingServices
545 = new ArrayList<ServiceRecord>();
546
547 /**
548 * List of services that are scheduled to restart following a crash.
549 */
550 final ArrayList<ServiceRecord> mRestartingServices
551 = new ArrayList<ServiceRecord>();
552
553 /**
554 * List of services that are in the process of being stopped.
555 */
556 final ArrayList<ServiceRecord> mStoppingServices
557 = new ArrayList<ServiceRecord>();
558
559 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700560 * Backup/restore process management
561 */
562 String mBackupAppName = null;
563 BackupRecord mBackupTarget = null;
564
565 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 * List of PendingThumbnailsRecord objects of clients who are still
567 * waiting to receive all of the thumbnails for a task.
568 */
569 final ArrayList mPendingThumbnails = new ArrayList();
570
571 /**
572 * List of HistoryRecord objects that have been finished and must
573 * still report back to a pending thumbnail receiver.
574 */
575 final ArrayList mCancelledThumbnails = new ArrayList();
576
Amith Yamasani742a6712011-05-04 14:49:28 -0700577 final ProviderMap mProviderMap = new ProviderMap();
578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 /**
580 * List of content providers who have clients waiting for them. The
581 * application is currently being launched and the provider will be
582 * removed from this list once it is published.
583 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700584 final ArrayList<ContentProviderRecord> mLaunchingProviders
585 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586
587 /**
588 * Global set of specific Uri permissions that have been granted.
589 */
590 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
591 = new SparseArray<HashMap<Uri, UriPermission>>();
592
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800593 CoreSettingsObserver mCoreSettingsObserver;
594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 /**
596 * Thread-local storage used to carry caller permissions over through
597 * indirect content-provider access.
598 * @see #ActivityManagerService.openContentUri()
599 */
600 private class Identity {
601 public int pid;
602 public int uid;
603
604 Identity(int _pid, int _uid) {
605 pid = _pid;
606 uid = _uid;
607 }
608 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
611
612 /**
613 * All information we have collected about the runtime performance of
614 * any user id that can impact battery performance.
615 */
616 final BatteryStatsService mBatteryStatsService;
617
618 /**
619 * information about component usage
620 */
621 final UsageStatsService mUsageStatsService;
622
623 /**
624 * Current configuration information. HistoryRecord objects are given
625 * a reference to this object to indicate which configuration they are
626 * currently running in, so this object must be kept immutable.
627 */
628 Configuration mConfiguration = new Configuration();
629
630 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800631 * Current sequencing integer of the configuration, for skipping old
632 * configurations.
633 */
634 int mConfigurationSeq = 0;
635
636 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700637 * Hardware-reported OpenGLES version.
638 */
639 final int GL_ES_VERSION;
640
641 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 * List of initialization arguments to pass to all processes when binding applications to them.
643 * For example, references to the commonly used services.
644 */
645 HashMap<String, IBinder> mAppBindArgs;
646
647 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700648 * Temporary to avoid allocations. Protected by main lock.
649 */
650 final StringBuilder mStringBuilder = new StringBuilder(256);
651
652 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 * Used to control how we initialize the service.
654 */
655 boolean mStartRunning = false;
656 ComponentName mTopComponent;
657 String mTopAction;
658 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700659 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 boolean mSystemReady = false;
661 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700662 boolean mWaitingUpdate = false;
663 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700664 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700665 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666
667 Context mContext;
668
669 int mFactoryTest;
670
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700671 boolean mCheckedForSetup;
672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700674 * The time at which we will allow normal application switches again,
675 * after a call to {@link #stopAppSwitches()}.
676 */
677 long mAppSwitchesAllowedTime;
678
679 /**
680 * This is set to true after the first switch after mAppSwitchesAllowedTime
681 * is set; any switches after that will clear the time.
682 */
683 boolean mDidAppSwitch;
684
685 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700686 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700687 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700688 long mLastPowerCheckRealtime;
689
690 /**
691 * Last time (in uptime) at which we checked for power usage.
692 */
693 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700694
695 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 * Set while we are wanting to sleep, to prevent any
697 * activities from being started/resumed.
698 */
699 boolean mSleeping = false;
700
701 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700702 * State of external calls telling us if the device is asleep.
703 */
704 boolean mWentToSleep = false;
705
706 /**
707 * State of external call telling us if the lock screen is shown.
708 */
709 boolean mLockScreenShown = false;
710
711 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700712 * Set if we are shutting down the system, similar to sleeping.
713 */
714 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715
716 /**
717 * Task identifier that activities are currently being started
718 * in. Incremented each time a new task is created.
719 * todo: Replace this with a TokenSpace class that generates non-repeating
720 * integers that won't wrap.
721 */
722 int mCurTask = 1;
723
724 /**
725 * Current sequence id for oom_adj computation traversal.
726 */
727 int mAdjSeq = 0;
728
729 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700730 * Current sequence id for process LRU updating.
731 */
732 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733
734 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700735 * Keep track of the number of service processes we last found, to
736 * determine on the next iteration which should be B services.
737 */
738 int mNumServiceProcs = 0;
739 int mNewNumServiceProcs = 0;
740
741 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 * System monitoring: number of processes that died since the last
743 * N procs were started.
744 */
745 int[] mProcDeaths = new int[20];
746
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700747 /**
748 * This is set if we had to do a delayed dexopt of an app before launching
749 * it, to increasing the ANR timeouts in that case.
750 */
751 boolean mDidDexOpt;
752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 String mDebugApp = null;
754 boolean mWaitForDebugger = false;
755 boolean mDebugTransient = false;
756 String mOrigDebugApp = null;
757 boolean mOrigWaitForDebugger = false;
758 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700759 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700760 String mProfileApp = null;
761 ProcessRecord mProfileProc = null;
762 String mProfileFile;
763 ParcelFileDescriptor mProfileFd;
764 int mProfileType = 0;
765 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800766 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700768 static class ProcessChangeItem {
769 static final int CHANGE_ACTIVITIES = 1<<0;
770 static final int CHANGE_IMPORTANCE= 1<<1;
771 int changes;
772 int uid;
773 int pid;
774 int importance;
775 boolean foregroundActivities;
776 }
777
Jeff Sharkeya4620792011-05-20 15:29:23 -0700778 final RemoteCallbackList<IProcessObserver> mProcessObservers
779 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700780 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
781
782 final ArrayList<ProcessChangeItem> mPendingProcessChanges
783 = new ArrayList<ProcessChangeItem>();
784 final ArrayList<ProcessChangeItem> mAvailProcessChanges
785 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 /**
788 * Callback of last caller to {@link #requestPss}.
789 */
790 Runnable mRequestPssCallback;
791
792 /**
793 * Remaining processes for which we are waiting results from the last
794 * call to {@link #requestPss}.
795 */
796 final ArrayList<ProcessRecord> mRequestPssList
797 = new ArrayList<ProcessRecord>();
798
799 /**
800 * Runtime statistics collection thread. This object's lock is used to
801 * protect all related state.
802 */
803 final Thread mProcessStatsThread;
804
805 /**
806 * Used to collect process stats when showing not responding dialog.
807 * Protected by mProcessStatsThread.
808 */
809 final ProcessStats mProcessStats = new ProcessStats(
810 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700811 final AtomicLong mLastCpuTime = new AtomicLong(0);
812 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 long mLastWriteTime = 0;
815
816 /**
817 * Set to true after the system has finished booting.
818 */
819 boolean mBooted = false;
820
Dianne Hackborn7d608422011-08-07 16:24:18 -0700821 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700822 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823
824 WindowManagerService mWindowManager;
825
826 static ActivityManagerService mSelf;
827 static ActivityThread mSystemThread;
828
829 private final class AppDeathRecipient implements IBinder.DeathRecipient {
830 final ProcessRecord mApp;
831 final int mPid;
832 final IApplicationThread mAppThread;
833
834 AppDeathRecipient(ProcessRecord app, int pid,
835 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800836 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 TAG, "New death recipient " + this
838 + " for thread " + thread.asBinder());
839 mApp = app;
840 mPid = pid;
841 mAppThread = thread;
842 }
843
844 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800845 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 TAG, "Death received in " + this
847 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 synchronized(ActivityManagerService.this) {
849 appDiedLocked(mApp, mPid, mAppThread);
850 }
851 }
852 }
853
854 static final int SHOW_ERROR_MSG = 1;
855 static final int SHOW_NOT_RESPONDING_MSG = 2;
856 static final int SHOW_FACTORY_ERROR_MSG = 3;
857 static final int UPDATE_CONFIGURATION_MSG = 4;
858 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
859 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 static final int SERVICE_TIMEOUT_MSG = 12;
861 static final int UPDATE_TIME_ZONE = 13;
862 static final int SHOW_UID_ERROR_MSG = 14;
863 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700865 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700866 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800867 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700868 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
869 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700870 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700871 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700872 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700873 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700874 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700875 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700876 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700877 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800879 static final int FIRST_ACTIVITY_STACK_MSG = 100;
880 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
881 static final int FIRST_COMPAT_MODE_MSG = 300;
882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700884 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700885 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886
887 final Handler mHandler = new Handler() {
888 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800889 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 //}
891
892 public void handleMessage(Message msg) {
893 switch (msg.what) {
894 case SHOW_ERROR_MSG: {
895 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 synchronized (ActivityManagerService.this) {
897 ProcessRecord proc = (ProcessRecord)data.get("app");
898 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800899 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 return;
901 }
902 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700903 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800904 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 d.show();
906 proc.crashDialog = d;
907 } else {
908 // The device is asleep, so just pretend that the user
909 // saw a crash dialog and hit "force quit".
910 res.set(0);
911 }
912 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700913
914 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 } break;
916 case SHOW_NOT_RESPONDING_MSG: {
917 synchronized (ActivityManagerService.this) {
918 HashMap data = (HashMap) msg.obj;
919 ProcessRecord proc = (ProcessRecord)data.get("app");
920 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800921 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 return;
923 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800924
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700925 Intent intent = new Intent("android.intent.action.ANR");
926 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800927 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
928 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700929 }
930 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800931 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700932 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800933
Justin Kohbc52ca22012-03-29 15:11:44 -0700934 if (mShowDialogs) {
935 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700936 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700937 d.show();
938 proc.anrDialog = d;
939 } else {
940 // Just kill the app if there is no dialog to be shown.
941 killAppAtUsersRequest(proc, null);
942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700944
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700945 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700947 case SHOW_STRICT_MODE_VIOLATION_MSG: {
948 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
949 synchronized (ActivityManagerService.this) {
950 ProcessRecord proc = (ProcessRecord) data.get("app");
951 if (proc == null) {
952 Slog.e(TAG, "App not found when showing strict mode dialog.");
953 break;
954 }
955 if (proc.crashDialog != null) {
956 Slog.e(TAG, "App already has strict mode dialog: " + proc);
957 return;
958 }
959 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700960 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700961 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
962 d.show();
963 proc.crashDialog = d;
964 } else {
965 // The device is asleep, so just pretend that the user
966 // saw a crash dialog and hit "force quit".
967 res.set(0);
968 }
969 }
970 ensureBootCompleted();
971 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 case SHOW_FACTORY_ERROR_MSG: {
973 Dialog d = new FactoryErrorDialog(
974 mContext, msg.getData().getCharSequence("msg"));
975 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700976 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 } break;
978 case UPDATE_CONFIGURATION_MSG: {
979 final ContentResolver resolver = mContext.getContentResolver();
980 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
981 } break;
982 case GC_BACKGROUND_PROCESSES_MSG: {
983 synchronized (ActivityManagerService.this) {
984 performAppGcsIfAppropriateLocked();
985 }
986 } break;
987 case WAIT_FOR_DEBUGGER_MSG: {
988 synchronized (ActivityManagerService.this) {
989 ProcessRecord app = (ProcessRecord)msg.obj;
990 if (msg.arg1 != 0) {
991 if (!app.waitedForDebugger) {
992 Dialog d = new AppWaitingForDebuggerDialog(
993 ActivityManagerService.this,
994 mContext, app);
995 app.waitDialog = d;
996 app.waitedForDebugger = true;
997 d.show();
998 }
999 } else {
1000 if (app.waitDialog != null) {
1001 app.waitDialog.dismiss();
1002 app.waitDialog = null;
1003 }
1004 }
1005 }
1006 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001008 if (mDidDexOpt) {
1009 mDidDexOpt = false;
1010 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1011 nmsg.obj = msg.obj;
1012 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
1013 return;
1014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 serviceTimeout((ProcessRecord)msg.obj);
1016 } break;
1017 case UPDATE_TIME_ZONE: {
1018 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001019 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1020 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 if (r.thread != null) {
1022 try {
1023 r.thread.updateTimeZone();
1024 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001025 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 }
1027 }
1028 }
1029 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001030 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001031 case CLEAR_DNS_CACHE: {
1032 synchronized (ActivityManagerService.this) {
1033 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1034 ProcessRecord r = mLruProcesses.get(i);
1035 if (r.thread != null) {
1036 try {
1037 r.thread.clearDnsCache();
1038 } catch (RemoteException ex) {
1039 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1040 }
1041 }
1042 }
1043 }
1044 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001045 case UPDATE_HTTP_PROXY: {
1046 ProxyProperties proxy = (ProxyProperties)msg.obj;
1047 String host = "";
1048 String port = "";
1049 String exclList = "";
1050 if (proxy != null) {
1051 host = proxy.getHost();
1052 port = Integer.toString(proxy.getPort());
1053 exclList = proxy.getExclusionList();
1054 }
1055 synchronized (ActivityManagerService.this) {
1056 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1057 ProcessRecord r = mLruProcesses.get(i);
1058 if (r.thread != null) {
1059 try {
1060 r.thread.setHttpProxy(host, port, exclList);
1061 } catch (RemoteException ex) {
1062 Slog.w(TAG, "Failed to update http proxy for: " +
1063 r.info.processName);
1064 }
1065 }
1066 }
1067 }
1068 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001070 String title = "System UIDs Inconsistent";
1071 String text = "UIDs on the system are inconsistent, you need to wipe your"
1072 + " data partition or your device will be unstable.";
1073 Log.e(TAG, title + ": " + text);
1074 if (mShowDialogs) {
1075 // XXX This is a temporary dialog, no need to localize.
1076 AlertDialog d = new BaseErrorDialog(mContext);
1077 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1078 d.setCancelable(false);
1079 d.setTitle(title);
1080 d.setMessage(text);
1081 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1082 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1083 mUidAlert = d;
1084 d.show();
1085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 } break;
1087 case IM_FEELING_LUCKY_MSG: {
1088 if (mUidAlert != null) {
1089 mUidAlert.dismiss();
1090 mUidAlert = null;
1091 }
1092 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001094 if (mDidDexOpt) {
1095 mDidDexOpt = false;
1096 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1097 nmsg.obj = msg.obj;
1098 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1099 return;
1100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 ProcessRecord app = (ProcessRecord)msg.obj;
1102 synchronized (ActivityManagerService.this) {
1103 processStartTimedOutLocked(app);
1104 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001105 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001106 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1107 synchronized (ActivityManagerService.this) {
1108 doPendingActivityLaunchesLocked(true);
1109 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001110 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001111 case KILL_APPLICATION_MSG: {
1112 synchronized (ActivityManagerService.this) {
1113 int uid = msg.arg1;
1114 boolean restart = (msg.arg2 == 1);
1115 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001116 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1117 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001118 }
1119 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001120 case FINALIZE_PENDING_INTENT_MSG: {
1121 ((PendingIntentRecord)msg.obj).completeFinalize();
1122 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001123 case POST_HEAVY_NOTIFICATION_MSG: {
1124 INotificationManager inm = NotificationManager.getService();
1125 if (inm == null) {
1126 return;
1127 }
1128
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001129 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001130 ProcessRecord process = root.app;
1131 if (process == null) {
1132 return;
1133 }
1134
1135 try {
1136 Context context = mContext.createPackageContext(process.info.packageName, 0);
1137 String text = mContext.getString(R.string.heavy_weight_notification,
1138 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1139 Notification notification = new Notification();
1140 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1141 notification.when = 0;
1142 notification.flags = Notification.FLAG_ONGOING_EVENT;
1143 notification.tickerText = text;
1144 notification.defaults = 0; // please be quiet
1145 notification.sound = null;
1146 notification.vibrate = null;
1147 notification.setLatestEventInfo(context, text,
1148 mContext.getText(R.string.heavy_weight_notification_detail),
1149 PendingIntent.getActivity(mContext, 0, root.intent,
1150 PendingIntent.FLAG_CANCEL_CURRENT));
1151
1152 try {
1153 int[] outId = new int[1];
1154 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1155 notification, outId);
1156 } catch (RuntimeException e) {
1157 Slog.w(ActivityManagerService.TAG,
1158 "Error showing notification for heavy-weight app", e);
1159 } catch (RemoteException e) {
1160 }
1161 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001162 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001163 }
1164 } break;
1165 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1166 INotificationManager inm = NotificationManager.getService();
1167 if (inm == null) {
1168 return;
1169 }
1170 try {
1171 inm.cancelNotification("android",
1172 R.string.heavy_weight_notification);
1173 } catch (RuntimeException e) {
1174 Slog.w(ActivityManagerService.TAG,
1175 "Error canceling notification for service", e);
1176 } catch (RemoteException e) {
1177 }
1178 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001179 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1180 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001181 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001182 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001183 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1184 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001185 }
1186 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001187 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1188 synchronized (ActivityManagerService.this) {
1189 ActivityRecord ar = (ActivityRecord)msg.obj;
1190 if (mCompatModeDialog != null) {
1191 if (mCompatModeDialog.mAppInfo.packageName.equals(
1192 ar.info.applicationInfo.packageName)) {
1193 return;
1194 }
1195 mCompatModeDialog.dismiss();
1196 mCompatModeDialog = null;
1197 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001198 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001199 if (mCompatModePackages.getPackageAskCompatModeLocked(
1200 ar.packageName)) {
1201 int mode = mCompatModePackages.computeCompatModeLocked(
1202 ar.info.applicationInfo);
1203 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1204 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1205 mCompatModeDialog = new CompatModeDialog(
1206 ActivityManagerService.this, mContext,
1207 ar.info.applicationInfo);
1208 mCompatModeDialog.show();
1209 }
1210 }
1211 }
1212 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001213 break;
1214 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001215 case DISPATCH_PROCESSES_CHANGED: {
1216 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001217 break;
1218 }
1219 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001220 final int pid = msg.arg1;
1221 final int uid = msg.arg2;
1222 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001223 break;
1224 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001225 case REPORT_MEM_USAGE: {
1226 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1227 if (!isDebuggable) {
1228 return;
1229 }
1230 synchronized (ActivityManagerService.this) {
1231 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001232 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1233 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001234 // avoid spamming.
1235 return;
1236 }
1237 mLastMemUsageReportTime = now;
1238 }
1239 Thread thread = new Thread() {
1240 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001241 StringBuilder dropBuilder = new StringBuilder(1024);
1242 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001243 StringWriter oomSw = new StringWriter();
1244 PrintWriter oomPw = new PrintWriter(oomSw);
1245 StringWriter catSw = new StringWriter();
1246 PrintWriter catPw = new PrintWriter(catSw);
1247 String[] emptyArgs = new String[] { };
1248 StringBuilder tag = new StringBuilder(128);
1249 StringBuilder stack = new StringBuilder(128);
1250 tag.append("Low on memory -- ");
1251 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1252 tag, stack);
1253 dropBuilder.append(stack);
1254 dropBuilder.append('\n');
1255 dropBuilder.append('\n');
1256 String oomString = oomSw.toString();
1257 dropBuilder.append(oomString);
1258 dropBuilder.append('\n');
1259 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001260 try {
1261 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1262 "procrank", });
1263 final InputStreamReader converter = new InputStreamReader(
1264 proc.getInputStream());
1265 BufferedReader in = new BufferedReader(converter);
1266 String line;
1267 while (true) {
1268 line = in.readLine();
1269 if (line == null) {
1270 break;
1271 }
1272 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001273 logBuilder.append(line);
1274 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001275 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001276 dropBuilder.append(line);
1277 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001278 }
1279 converter.close();
1280 } catch (IOException e) {
1281 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001282 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001283 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001284 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001285 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001286 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001287 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001288 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001289 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001290 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001291 addErrorToDropBox("lowmem", null, "system_server", null,
1292 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001293 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001294 synchronized (ActivityManagerService.this) {
1295 long now = SystemClock.uptimeMillis();
1296 if (mLastMemUsageReportTime < now) {
1297 mLastMemUsageReportTime = now;
1298 }
1299 }
1300 }
1301 };
1302 thread.start();
1303 break;
1304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 }
1306 }
1307 };
1308
1309 public static void setSystemProcess() {
1310 try {
1311 ActivityManagerService m = mSelf;
1312
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001313 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001315 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001316 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 if (MONITOR_CPU_USAGE) {
1318 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 ServiceManager.addService("permission", new PermissionController(m));
1321
1322 ApplicationInfo info =
1323 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001324 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001325 mSystemThread.installSystemApplicationInfo(info);
1326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 synchronized (mSelf) {
1328 ProcessRecord app = mSelf.newProcessRecordLocked(
1329 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001330 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001332 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001333 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001334 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 synchronized (mSelf.mPidsSelfLocked) {
1336 mSelf.mPidsSelfLocked.put(app.pid, app);
1337 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001338 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
1340 } catch (PackageManager.NameNotFoundException e) {
1341 throw new RuntimeException(
1342 "Unable to find android system package", e);
1343 }
1344 }
1345
1346 public void setWindowManager(WindowManagerService wm) {
1347 mWindowManager = wm;
1348 }
1349
1350 public static final Context main(int factoryTest) {
1351 AThread thr = new AThread();
1352 thr.start();
1353
1354 synchronized (thr) {
1355 while (thr.mService == null) {
1356 try {
1357 thr.wait();
1358 } catch (InterruptedException e) {
1359 }
1360 }
1361 }
1362
1363 ActivityManagerService m = thr.mService;
1364 mSelf = m;
1365 ActivityThread at = ActivityThread.systemMain();
1366 mSystemThread = at;
1367 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001368 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 m.mContext = context;
1370 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001371 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372
1373 m.mBatteryStatsService.publish(context);
1374 m.mUsageStatsService.publish(context);
1375
1376 synchronized (thr) {
1377 thr.mReady = true;
1378 thr.notifyAll();
1379 }
1380
1381 m.startRunning(null, null, null, null);
1382
1383 return context;
1384 }
1385
1386 public static ActivityManagerService self() {
1387 return mSelf;
1388 }
1389
1390 static class AThread extends Thread {
1391 ActivityManagerService mService;
1392 boolean mReady = false;
1393
1394 public AThread() {
1395 super("ActivityManager");
1396 }
1397
1398 public void run() {
1399 Looper.prepare();
1400
1401 android.os.Process.setThreadPriority(
1402 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001403 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404
1405 ActivityManagerService m = new ActivityManagerService();
1406
1407 synchronized (this) {
1408 mService = m;
1409 notifyAll();
1410 }
1411
1412 synchronized (this) {
1413 while (!mReady) {
1414 try {
1415 wait();
1416 } catch (InterruptedException e) {
1417 }
1418 }
1419 }
1420
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001421 // For debug builds, log event loop stalls to dropbox for analysis.
1422 if (StrictMode.conditionallyEnableDebugLogging()) {
1423 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1424 }
1425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 Looper.loop();
1427 }
1428 }
1429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 static class MemBinder extends Binder {
1431 ActivityManagerService mActivityManagerService;
1432 MemBinder(ActivityManagerService activityManagerService) {
1433 mActivityManagerService = activityManagerService;
1434 }
1435
1436 @Override
1437 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001438 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1439 != PackageManager.PERMISSION_GRANTED) {
1440 pw.println("Permission Denial: can't dump meminfo from from pid="
1441 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1442 + " without permission " + android.Manifest.permission.DUMP);
1443 return;
1444 }
1445
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001446 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001447 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 }
1449 }
1450
Chet Haase9c1e23b2011-03-24 10:51:31 -07001451 static class GraphicsBinder extends Binder {
1452 ActivityManagerService mActivityManagerService;
1453 GraphicsBinder(ActivityManagerService activityManagerService) {
1454 mActivityManagerService = activityManagerService;
1455 }
1456
1457 @Override
1458 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001459 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1460 != PackageManager.PERMISSION_GRANTED) {
1461 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1462 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1463 + " without permission " + android.Manifest.permission.DUMP);
1464 return;
1465 }
1466
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001467 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001468 }
1469 }
1470
Jeff Brown6754ba22011-12-14 20:20:01 -08001471 static class DbBinder extends Binder {
1472 ActivityManagerService mActivityManagerService;
1473 DbBinder(ActivityManagerService activityManagerService) {
1474 mActivityManagerService = activityManagerService;
1475 }
1476
1477 @Override
1478 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1479 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1480 != PackageManager.PERMISSION_GRANTED) {
1481 pw.println("Permission Denial: can't dump dbinfo from from pid="
1482 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1483 + " without permission " + android.Manifest.permission.DUMP);
1484 return;
1485 }
1486
1487 mActivityManagerService.dumpDbInfo(fd, pw, args);
1488 }
1489 }
1490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 static class CpuBinder extends Binder {
1492 ActivityManagerService mActivityManagerService;
1493 CpuBinder(ActivityManagerService activityManagerService) {
1494 mActivityManagerService = activityManagerService;
1495 }
1496
1497 @Override
1498 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001499 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1500 != PackageManager.PERMISSION_GRANTED) {
1501 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1502 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1503 + " without permission " + android.Manifest.permission.DUMP);
1504 return;
1505 }
1506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001508 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1509 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1510 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512 }
1513 }
1514
1515 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001516 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001517
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001518 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1519 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1520 mBroadcastQueues[0] = mFgBroadcastQueue;
1521 mBroadcastQueues[1] = mBgBroadcastQueue;
1522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 File dataDir = Environment.getDataDirectory();
1524 File systemDir = new File(dataDir, "system");
1525 systemDir.mkdirs();
1526 mBatteryStatsService = new BatteryStatsService(new File(
1527 systemDir, "batterystats.bin").toString());
1528 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001529 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001530 mOnBattery = DEBUG_POWER ? true
1531 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001532 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001534 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001535 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001536 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537
Jack Palevichb90d28c2009-07-22 15:35:24 -07001538 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1539 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1540
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001541 mConfiguration.setToDefaults();
1542 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001543 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 mProcessStats.init();
1545
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001546 mCompatModePackages = new CompatModePackages(this, systemDir);
1547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 // Add ourself to the Watchdog monitors.
1549 Watchdog.getInstance().addMonitor(this);
1550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 mProcessStatsThread = new Thread("ProcessStats") {
1552 public void run() {
1553 while (true) {
1554 try {
1555 try {
1556 synchronized(this) {
1557 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001558 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001560 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 // + ", write delay=" + nextWriteDelay);
1562 if (nextWriteDelay < nextCpuDelay) {
1563 nextCpuDelay = nextWriteDelay;
1564 }
1565 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001566 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 this.wait(nextCpuDelay);
1568 }
1569 }
1570 } catch (InterruptedException e) {
1571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 updateCpuStatsNow();
1573 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001574 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 }
1576 }
1577 }
1578 };
1579 mProcessStatsThread.start();
1580 }
1581
1582 @Override
1583 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1584 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001585 if (code == SYSPROPS_TRANSACTION) {
1586 // We need to tell all apps about the system property change.
1587 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1588 synchronized(this) {
1589 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1590 final int NA = apps.size();
1591 for (int ia=0; ia<NA; ia++) {
1592 ProcessRecord app = apps.valueAt(ia);
1593 if (app.thread != null) {
1594 procs.add(app.thread.asBinder());
1595 }
1596 }
1597 }
1598 }
1599
1600 int N = procs.size();
1601 for (int i=0; i<N; i++) {
1602 Parcel data2 = Parcel.obtain();
1603 try {
1604 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1605 } catch (RemoteException e) {
1606 }
1607 data2.recycle();
1608 }
1609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 try {
1611 return super.onTransact(code, data, reply, flags);
1612 } catch (RuntimeException e) {
1613 // The activity manager only throws security exceptions, so let's
1614 // log all others.
1615 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001616 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 }
1618 throw e;
1619 }
1620 }
1621
1622 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001623 final long now = SystemClock.uptimeMillis();
1624 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1625 return;
1626 }
1627 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1628 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 mProcessStatsThread.notify();
1630 }
1631 }
1632 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 void updateCpuStatsNow() {
1635 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001636 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 final long now = SystemClock.uptimeMillis();
1638 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001641 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1642 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 haveNewCpuStats = true;
1644 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001645 //Slog.i(TAG, mProcessStats.printCurrentState());
1646 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 // + mProcessStats.getTotalCpuPercent() + "%");
1648
Joe Onorato8a9b2202010-02-26 18:56:32 -08001649 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 if ("true".equals(SystemProperties.get("events.cpu"))) {
1651 int user = mProcessStats.getLastUserTime();
1652 int system = mProcessStats.getLastSystemTime();
1653 int iowait = mProcessStats.getLastIoWaitTime();
1654 int irq = mProcessStats.getLastIrqTime();
1655 int softIrq = mProcessStats.getLastSoftIrqTime();
1656 int idle = mProcessStats.getLastIdleTime();
1657
1658 int total = user + system + iowait + irq + softIrq + idle;
1659 if (total == 0) total = 1;
1660
Doug Zongker2bec3d42009-12-04 12:52:44 -08001661 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 ((user+system+iowait+irq+softIrq) * 100) / total,
1663 (user * 100) / total,
1664 (system * 100) / total,
1665 (iowait * 100) / total,
1666 (irq * 100) / total,
1667 (softIrq * 100) / total);
1668 }
1669 }
1670
Amith Yamasanie43530a2009-08-21 13:11:37 -07001671 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001672 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001673 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 synchronized(mPidsSelfLocked) {
1675 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001676 if (mOnBattery) {
1677 int perc = bstats.startAddingCpuLocked();
1678 int totalUTime = 0;
1679 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001680 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001682 ProcessStats.Stats st = mProcessStats.getStats(i);
1683 if (!st.working) {
1684 continue;
1685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001687 int otherUTime = (st.rel_utime*perc)/100;
1688 int otherSTime = (st.rel_stime*perc)/100;
1689 totalUTime += otherUTime;
1690 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 if (pr != null) {
1692 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001693 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1694 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001695 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001696 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001697 } else {
1698 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001699 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001700 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001701 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1702 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001703 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 }
1706 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001707 bstats.finishAddingCpuLocked(perc, totalUTime,
1708 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 }
1710 }
1711 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1714 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001715 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 }
1717 }
1718 }
1719 }
1720
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001721 @Override
1722 public void batteryNeedsCpuUpdate() {
1723 updateCpuStatsNow();
1724 }
1725
1726 @Override
1727 public void batteryPowerChanged(boolean onBattery) {
1728 // When plugging in, update the CPU stats first before changing
1729 // the plug state.
1730 updateCpuStatsNow();
1731 synchronized (this) {
1732 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001733 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001734 }
1735 }
1736 }
1737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 /**
1739 * Initialize the application bind args. These are passed to each
1740 * process when the bindApplication() IPC is sent to the process. They're
1741 * lazily setup to make sure the services are running when they're asked for.
1742 */
1743 private HashMap<String, IBinder> getCommonServicesLocked() {
1744 if (mAppBindArgs == null) {
1745 mAppBindArgs = new HashMap<String, IBinder>();
1746
1747 // Setup the application init args
1748 mAppBindArgs.put("package", ServiceManager.getService("package"));
1749 mAppBindArgs.put("window", ServiceManager.getService("window"));
1750 mAppBindArgs.put(Context.ALARM_SERVICE,
1751 ServiceManager.getService(Context.ALARM_SERVICE));
1752 }
1753 return mAppBindArgs;
1754 }
1755
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001756 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 if (mFocusedActivity != r) {
1758 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001759 if (r != null) {
1760 mWindowManager.setFocusedApp(r.appToken, true);
1761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 }
1763 }
1764
Dianne Hackborn906497c2010-05-10 15:57:38 -07001765 private final void updateLruProcessInternalLocked(ProcessRecord app,
1766 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001768 int lrui = mLruProcesses.indexOf(app);
1769 if (lrui >= 0) mLruProcesses.remove(lrui);
1770
1771 int i = mLruProcesses.size()-1;
1772 int skipTop = 0;
1773
Dianne Hackborn906497c2010-05-10 15:57:38 -07001774 app.lruSeq = mLruSeq;
1775
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001776 // compute the new weight for this process.
1777 if (updateActivityTime) {
1778 app.lastActivityTime = SystemClock.uptimeMillis();
1779 }
1780 if (app.activities.size() > 0) {
1781 // If this process has activities, we more strongly want to keep
1782 // it around.
1783 app.lruWeight = app.lastActivityTime;
1784 } else if (app.pubProviders.size() > 0) {
1785 // If this process contains content providers, we want to keep
1786 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001787 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001788 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001789 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001790 } else {
1791 // If this process doesn't have activities, we less strongly
1792 // want to keep it around, and generally want to avoid getting
1793 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001794 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001795 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001796 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001797 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001798
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001799 while (i >= 0) {
1800 ProcessRecord p = mLruProcesses.get(i);
1801 // If this app shouldn't be in front of the first N background
1802 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001803 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001804 skipTop--;
1805 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001806 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001807 mLruProcesses.add(i+1, app);
1808 break;
1809 }
1810 i--;
1811 }
1812 if (i < 0) {
1813 mLruProcesses.add(0, app);
1814 }
1815
Dianne Hackborn906497c2010-05-10 15:57:38 -07001816 // If the app is currently using a content provider or service,
1817 // bump those processes as well.
1818 if (app.connections.size() > 0) {
1819 for (ConnectionRecord cr : app.connections) {
1820 if (cr.binding != null && cr.binding.service != null
1821 && cr.binding.service.app != null
1822 && cr.binding.service.app.lruSeq != mLruSeq) {
1823 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1824 updateActivityTime, i+1);
1825 }
1826 }
1827 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001828 for (int j=app.conProviders.size()-1; j>=0; j--) {
1829 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1830 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1831 updateLruProcessInternalLocked(cpr.proc, oomAdj,
1832 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001833 }
1834 }
1835
Joe Onorato8a9b2202010-02-26 18:56:32 -08001836 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 if (oomAdj) {
1838 updateOomAdjLocked();
1839 }
1840 }
1841
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001842 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001843 boolean oomAdj, boolean updateActivityTime) {
1844 mLruSeq++;
1845 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1846 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001847
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001848 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001850 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001851 // The system gets to run in any process. If there are multiple
1852 // processes with the same uid, just pick the first (this
1853 // should never happen).
1854 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1855 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001856 if (procs == null) return null;
1857 final int N = procs.size();
1858 for (int i = 0; i < N; i++) {
1859 if (UserId.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
1860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 }
1862 ProcessRecord proc = mProcessNames.get(processName, uid);
1863 return proc;
1864 }
1865
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001866 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001867 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001868 try {
1869 if (pm.performDexOpt(packageName)) {
1870 mDidDexOpt = true;
1871 }
1872 } catch (RemoteException e) {
1873 }
1874 }
1875
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001876 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 int transit = mWindowManager.getPendingAppTransition();
1878 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1879 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1880 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1881 }
1882
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001883 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001885 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1886 boolean isolated) {
1887 ProcessRecord app;
1888 if (!isolated) {
1889 app = getProcessRecordLocked(processName, info.uid);
1890 } else {
1891 // If this is an isolated process, it can't re-use an existing process.
1892 app = null;
1893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 // We don't have to do anything more if:
1895 // (1) There is an existing application record; and
1896 // (2) The caller doesn't think it is dead, OR there is no thread
1897 // object attached to it so we know it couldn't have crashed; and
1898 // (3) There is a pid assigned to it, so it is either starting or
1899 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001900 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 + " app=" + app + " knownToBeDead=" + knownToBeDead
1902 + " thread=" + (app != null ? app.thread : null)
1903 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001904 if (app != null && app.pid > 0) {
1905 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001906 // We already have the app running, or are waiting for it to
1907 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001908 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001909 // If this is a new package in the process, add the package to the list
1910 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001911 return app;
1912 } else {
1913 // An application record is attached to a previous process,
1914 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001915 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001916 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 String hostingNameStr = hostingName != null
1921 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001922
1923 if (!isolated) {
1924 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1925 // If we are in the background, then check to see if this process
1926 // is bad. If so, we will just silently fail.
1927 if (mBadProcesses.get(info.processName, info.uid) != null) {
1928 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1929 + "/" + info.processName);
1930 return null;
1931 }
1932 } else {
1933 // When the user is explicitly starting a process, then clear its
1934 // crash count so that we won't make it bad until they see at
1935 // least one crash dialog again, and make the process good again
1936 // if it had been bad.
1937 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001938 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001939 mProcessCrashTimes.remove(info.processName, info.uid);
1940 if (mBadProcesses.get(info.processName, info.uid) != null) {
1941 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1942 info.processName);
1943 mBadProcesses.remove(info.processName, info.uid);
1944 if (app != null) {
1945 app.bad = false;
1946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 }
1948 }
1949 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001952 app = newProcessRecordLocked(null, info, processName, isolated);
1953 if (app == null) {
1954 Slog.w(TAG, "Failed making new process record for "
1955 + processName + "/" + info.uid + " isolated=" + isolated);
1956 return null;
1957 }
1958 mProcessNames.put(processName, app.uid, app);
1959 if (isolated) {
1960 mIsolatedProcesses.put(app.uid, app);
1961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 } else {
1963 // If this is a new package in the process, add the package to the list
1964 app.addPackage(info.packageName);
1965 }
1966
1967 // If the system is not ready yet, then hold off on starting this
1968 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001969 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001970 && !isAllowedWhileBooting(info)
1971 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 if (!mProcessesOnHold.contains(app)) {
1973 mProcessesOnHold.add(app);
1974 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001975 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 return app;
1977 }
1978
1979 startProcessLocked(app, hostingType, hostingNameStr);
1980 return (app.pid != 0) ? app : null;
1981 }
1982
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001983 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1984 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1985 }
1986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 private final void startProcessLocked(ProcessRecord app,
1988 String hostingType, String hostingNameStr) {
1989 if (app.pid > 0 && app.pid != MY_PID) {
1990 synchronized (mPidsSelfLocked) {
1991 mPidsSelfLocked.remove(app.pid);
1992 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1993 }
1994 app.pid = 0;
1995 }
1996
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001997 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1998 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 mProcessesOnHold.remove(app);
2000
2001 updateCpuStats();
2002
2003 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2004 mProcDeaths[0] = 0;
2005
2006 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002007 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002010 if (!app.isolated) {
2011 try {
2012 gids = mContext.getPackageManager().getPackageGids(
2013 app.info.packageName);
2014 } catch (PackageManager.NameNotFoundException e) {
2015 Slog.w(TAG, "Unable to retrieve gids", e);
2016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 }
2018 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2019 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2020 && mTopComponent != null
2021 && app.processName.equals(mTopComponent.getPackageName())) {
2022 uid = 0;
2023 }
2024 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2025 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2026 uid = 0;
2027 }
2028 }
2029 int debugFlags = 0;
2030 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2031 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002032 // Also turn on CheckJNI for debuggable apps. It's quite
2033 // awkward to turn on otherwise.
2034 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002036 // Run the app in safe mode if its manifest requests so or the
2037 // system is booted in safe mode.
2038 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2039 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002040 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2043 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2044 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002045 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2046 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 if ("1".equals(SystemProperties.get("debug.assert"))) {
2049 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2050 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002051
2052 // Start the process. It will either succeed and return a result containing
2053 // the PID of the new process, or else throw a RuntimeException.
2054 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002055 app.processName, uid, uid, gids, debugFlags,
2056 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2059 synchronized (bs) {
2060 if (bs.isOnBattery()) {
2061 app.batteryStats.incStartsLocked();
2062 }
2063 }
2064
Jeff Brown3f9dd282011-07-08 20:02:19 -07002065 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 app.processName, hostingType,
2067 hostingNameStr != null ? hostingNameStr : "");
2068
2069 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002070 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002073 StringBuilder buf = mStringBuilder;
2074 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 buf.append("Start proc ");
2076 buf.append(app.processName);
2077 buf.append(" for ");
2078 buf.append(hostingType);
2079 if (hostingNameStr != null) {
2080 buf.append(" ");
2081 buf.append(hostingNameStr);
2082 }
2083 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002084 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 buf.append(" uid=");
2086 buf.append(uid);
2087 buf.append(" gids={");
2088 if (gids != null) {
2089 for (int gi=0; gi<gids.length; gi++) {
2090 if (gi != 0) buf.append(", ");
2091 buf.append(gids[gi]);
2092
2093 }
2094 }
2095 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002096 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002097 app.pid = startResult.pid;
2098 app.usingWrapper = startResult.usingWrapper;
2099 app.removed = false;
2100 synchronized (mPidsSelfLocked) {
2101 this.mPidsSelfLocked.put(startResult.pid, app);
2102 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2103 msg.obj = app;
2104 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2105 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 }
2107 } catch (RuntimeException e) {
2108 // XXX do better error recovery.
2109 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002110 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 }
2112 }
2113
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002114 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 if (resumed) {
2116 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2117 } else {
2118 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2119 }
2120 }
2121
Amith Yamasani742a6712011-05-04 14:49:28 -07002122 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002123 if (mHeadless) {
2124 // Added because none of the other calls to ensureBootCompleted seem to fire
2125 // when running headless.
2126 ensureBootCompleted();
2127 return false;
2128 }
2129
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002130 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2131 && mTopAction == null) {
2132 // We are running in factory test mode, but unable to find
2133 // the factory test app, so just sit around displaying the
2134 // error message and don't try to start anything.
2135 return false;
2136 }
2137 Intent intent = new Intent(
2138 mTopAction,
2139 mTopData != null ? Uri.parse(mTopData) : null);
2140 intent.setComponent(mTopComponent);
2141 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2142 intent.addCategory(Intent.CATEGORY_HOME);
2143 }
2144 ActivityInfo aInfo =
2145 intent.resolveActivityInfo(mContext.getPackageManager(),
2146 STOCK_PM_FLAGS);
2147 if (aInfo != null) {
2148 intent.setComponent(new ComponentName(
2149 aInfo.applicationInfo.packageName, aInfo.name));
2150 // Don't do this if the home app is currently being
2151 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002152 aInfo = new ActivityInfo(aInfo);
2153 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002154 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2155 aInfo.applicationInfo.uid);
2156 if (app == null || app.instrumentationClass == null) {
2157 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002158 mMainStack.startActivityLocked(null, intent, null, aInfo,
2159 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002160 }
2161 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002162
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002163 return true;
2164 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002165
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002166 /**
2167 * Starts the "new version setup screen" if appropriate.
2168 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002169 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002170 // Only do this once per boot.
2171 if (mCheckedForSetup) {
2172 return;
2173 }
2174
2175 // We will show this screen if the current one is a different
2176 // version than the last one shown, and we are not running in
2177 // low-level factory test mode.
2178 final ContentResolver resolver = mContext.getContentResolver();
2179 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2180 Settings.Secure.getInt(resolver,
2181 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2182 mCheckedForSetup = true;
2183
2184 // See if we should be showing the platform update setup UI.
2185 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2186 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2187 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2188
2189 // We don't allow third party apps to replace this.
2190 ResolveInfo ri = null;
2191 for (int i=0; ris != null && i<ris.size(); i++) {
2192 if ((ris.get(i).activityInfo.applicationInfo.flags
2193 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2194 ri = ris.get(i);
2195 break;
2196 }
2197 }
2198
2199 if (ri != null) {
2200 String vers = ri.activityInfo.metaData != null
2201 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2202 : null;
2203 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2204 vers = ri.activityInfo.applicationInfo.metaData.getString(
2205 Intent.METADATA_SETUP_VERSION);
2206 }
2207 String lastVers = Settings.Secure.getString(
2208 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2209 if (vers != null && !vers.equals(lastVers)) {
2210 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2211 intent.setComponent(new ComponentName(
2212 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002213 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2214 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002215 }
2216 }
2217 }
2218 }
2219
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002220 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002221 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002222 }
2223
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002224 void enforceNotIsolatedCaller(String caller) {
2225 if (UserId.isIsolated(Binder.getCallingUid())) {
2226 throw new SecurityException("Isolated process not allowed to call " + caller);
2227 }
2228 }
2229
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002230 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002231 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002232 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002233 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2234 }
2235 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002236
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002237 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002238 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2239 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002240 synchronized (this) {
2241 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2242 }
2243 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002244
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002245 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002246 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002247 synchronized (this) {
2248 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2249 }
2250 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002251
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002252 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002253 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2254 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002255 synchronized (this) {
2256 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002257 }
2258 }
2259
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002260 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002261 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002262 synchronized (this) {
2263 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2264 }
2265 }
2266
2267 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002268 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2269 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002270 synchronized (this) {
2271 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2272 }
2273 }
2274
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002275 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002276 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002277 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002280 private void dispatchProcessesChanged() {
2281 int N;
2282 synchronized (this) {
2283 N = mPendingProcessChanges.size();
2284 if (mActiveProcessChanges.length < N) {
2285 mActiveProcessChanges = new ProcessChangeItem[N];
2286 }
2287 mPendingProcessChanges.toArray(mActiveProcessChanges);
2288 mAvailProcessChanges.addAll(mPendingProcessChanges);
2289 mPendingProcessChanges.clear();
2290 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2291 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002292 int i = mProcessObservers.beginBroadcast();
2293 while (i > 0) {
2294 i--;
2295 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2296 if (observer != null) {
2297 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002298 for (int j=0; j<N; j++) {
2299 ProcessChangeItem item = mActiveProcessChanges[j];
2300 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2301 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2302 + item.pid + " uid=" + item.uid + ": "
2303 + item.foregroundActivities);
2304 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2305 item.foregroundActivities);
2306 }
2307 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2308 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2309 + item.pid + " uid=" + item.uid + ": " + item.importance);
2310 observer.onImportanceChanged(item.pid, item.uid,
2311 item.importance);
2312 }
2313 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002314 } catch (RemoteException e) {
2315 }
2316 }
2317 }
2318 mProcessObservers.finishBroadcast();
2319 }
2320
2321 private void dispatchProcessDied(int pid, int uid) {
2322 int i = mProcessObservers.beginBroadcast();
2323 while (i > 0) {
2324 i--;
2325 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2326 if (observer != null) {
2327 try {
2328 observer.onProcessDied(pid, uid);
2329 } catch (RemoteException e) {
2330 }
2331 }
2332 }
2333 mProcessObservers.finishBroadcast();
2334 }
2335
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002336 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002337 final int N = mPendingActivityLaunches.size();
2338 if (N <= 0) {
2339 return;
2340 }
2341 for (int i=0; i<N; i++) {
2342 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002343 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002344 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002345 }
2346 mPendingActivityLaunches.clear();
2347 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002348
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002349 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002350 Intent intent, String resolvedType, IBinder resultTo,
2351 String resultWho, int requestCode, int startFlags,
2352 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002353 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002354 int userId = 0;
2355 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2356 // Requesting home, set the identity to the current user
2357 // HACK!
2358 userId = mCurrentUserId;
2359 } else {
2360 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2361 // the current user's userId
2362 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2363 userId = 0;
2364 } else {
2365 userId = Binder.getOrigCallingUser();
2366 }
2367 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002368 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002369 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2370 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002371 }
2372
2373 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002374 Intent intent, String resolvedType, IBinder resultTo,
2375 String resultWho, int requestCode, int startFlags, String profileFile,
2376 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002377 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002378 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002379 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002380 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002381 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2382 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002383 return res;
2384 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002385
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002386 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002387 Intent intent, String resolvedType, IBinder resultTo,
2388 String resultWho, int requestCode, int startFlags, Configuration config,
2389 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002390 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002391 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002392 resultTo, resultWho, requestCode, startFlags,
2393 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002394 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002395 }
2396
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002397 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002398 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002399 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002400 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002401 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002402 // Refuse possible leaked file descriptors
2403 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2404 throw new IllegalArgumentException("File descriptors passed in Intent");
2405 }
2406
2407 IIntentSender sender = intent.getTarget();
2408 if (!(sender instanceof PendingIntentRecord)) {
2409 throw new IllegalArgumentException("Bad PendingIntent object");
2410 }
2411
2412 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002413
2414 synchronized (this) {
2415 // If this is coming from the currently resumed activity, it is
2416 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002417 if (mMainStack.mResumedActivity != null
2418 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002419 Binder.getCallingUid()) {
2420 mAppSwitchesAllowedTime = 0;
2421 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002422 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002423 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2424 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002425 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002426 }
2427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002429 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 // Refuse possible leaked file descriptors
2431 if (intent != null && intent.hasFileDescriptors() == true) {
2432 throw new IllegalArgumentException("File descriptors passed in Intent");
2433 }
2434
2435 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002436 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2437 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002438 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 return false;
2440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 if (r.app == null || r.app.thread == null) {
2442 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002443 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 return false;
2445 }
2446 intent = new Intent(intent);
2447 // The caller is not allowed to change the data.
2448 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2449 // And we are resetting to find the next component...
2450 intent.setComponent(null);
2451
2452 ActivityInfo aInfo = null;
2453 try {
2454 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002455 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002457 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2458 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459
2460 // Look for the original activity in the list...
2461 final int N = resolves != null ? resolves.size() : 0;
2462 for (int i=0; i<N; i++) {
2463 ResolveInfo rInfo = resolves.get(i);
2464 if (rInfo.activityInfo.packageName.equals(r.packageName)
2465 && rInfo.activityInfo.name.equals(r.info.name)) {
2466 // We found the current one... the next matching is
2467 // after it.
2468 i++;
2469 if (i<N) {
2470 aInfo = resolves.get(i).activityInfo;
2471 }
2472 break;
2473 }
2474 }
2475 } catch (RemoteException e) {
2476 }
2477
2478 if (aInfo == null) {
2479 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002480 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 return false;
2482 }
2483
2484 intent.setComponent(new ComponentName(
2485 aInfo.applicationInfo.packageName, aInfo.name));
2486 intent.setFlags(intent.getFlags()&~(
2487 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2488 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2489 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2490 Intent.FLAG_ACTIVITY_NEW_TASK));
2491
2492 // Okay now we need to start the new activity, replacing the
2493 // currently running activity. This is a little tricky because
2494 // we want to start the new one as if the current one is finished,
2495 // but not finish the current one first so that there is no flicker.
2496 // And thus...
2497 final boolean wasFinishing = r.finishing;
2498 r.finishing = true;
2499
2500 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002501 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 final String resultWho = r.resultWho;
2503 final int requestCode = r.requestCode;
2504 r.resultTo = null;
2505 if (resultTo != null) {
2506 resultTo.removeResultsLocked(r, resultWho, requestCode);
2507 }
2508
2509 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002510 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002511 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2512 resultWho, requestCode, -1, r.launchedFromUid, 0,
2513 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 Binder.restoreCallingIdentity(origId);
2515
2516 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002517 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 return false;
2519 }
2520 return true;
2521 }
2522 }
2523
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002524 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002526 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002527
2528 // This is so super not safe, that only the system (or okay root)
2529 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002530 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002531 final int callingUid = Binder.getCallingUid();
2532 if (callingUid != 0 && callingUid != Process.myUid()) {
2533 throw new SecurityException(
2534 "startActivityInPackage only available to the system");
2535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536
Amith Yamasani742a6712011-05-04 14:49:28 -07002537 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002538 resultTo, resultWho, requestCode, startFlags,
2539 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002540 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002541 }
2542
2543 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002544 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002545 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002546 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002547 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002548 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002549 }
2550
2551 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002552 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2553 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002554
2555 // This is so super not safe, that only the system (or okay root)
2556 // can do it.
2557 final int callingUid = Binder.getCallingUid();
2558 if (callingUid != 0 && callingUid != Process.myUid()) {
2559 throw new SecurityException(
2560 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002562 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002563 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002564 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 }
2566
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002567 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002569 // Quick case: check if the top-most recent task is the same.
2570 if (N > 0 && mRecentTasks.get(0) == task) {
2571 return;
2572 }
2573 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 for (int i=0; i<N; i++) {
2575 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002576 if (task.userId == tr.userId
2577 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2578 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 mRecentTasks.remove(i);
2580 i--;
2581 N--;
2582 if (task.intent == null) {
2583 // If the new recent task we are adding is not fully
2584 // specified, then replace it with the existing recent task.
2585 task = tr;
2586 }
2587 }
2588 }
2589 if (N >= MAX_RECENT_TASKS) {
2590 mRecentTasks.remove(N-1);
2591 }
2592 mRecentTasks.add(0, task);
2593 }
2594
2595 public void setRequestedOrientation(IBinder token,
2596 int requestedOrientation) {
2597 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002598 ActivityRecord r = mMainStack.isInStackLocked(token);
2599 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 return;
2601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002603 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002605 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002606 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 if (config != null) {
2608 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002609 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002610 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 }
2612 }
2613 Binder.restoreCallingIdentity(origId);
2614 }
2615 }
2616
2617 public int getRequestedOrientation(IBinder token) {
2618 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002619 ActivityRecord r = mMainStack.isInStackLocked(token);
2620 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2622 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002623 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 }
2625 }
2626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 /**
2628 * This is the internal entry point for handling Activity.finish().
2629 *
2630 * @param token The Binder token referencing the Activity we want to finish.
2631 * @param resultCode Result code, if any, from this Activity.
2632 * @param resultData Result data (Intent), if any, from this Activity.
2633 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002634 * @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 -08002635 */
2636 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2637 // Refuse possible leaked file descriptors
2638 if (resultData != null && resultData.hasFileDescriptors() == true) {
2639 throw new IllegalArgumentException("File descriptors passed in Intent");
2640 }
2641
2642 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002643 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002645 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 if (next != null) {
2647 // ask watcher if this is allowed
2648 boolean resumeOK = true;
2649 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002650 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002652 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 }
2654
2655 if (!resumeOK) {
2656 return false;
2657 }
2658 }
2659 }
2660 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002661 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 resultData, "app-request");
2663 Binder.restoreCallingIdentity(origId);
2664 return res;
2665 }
2666 }
2667
Dianne Hackborn860755f2010-06-03 18:47:52 -07002668 public final void finishHeavyWeightApp() {
2669 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2670 != PackageManager.PERMISSION_GRANTED) {
2671 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2672 + Binder.getCallingPid()
2673 + ", uid=" + Binder.getCallingUid()
2674 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2675 Slog.w(TAG, msg);
2676 throw new SecurityException(msg);
2677 }
2678
2679 synchronized(this) {
2680 if (mHeavyWeightProcess == null) {
2681 return;
2682 }
2683
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002684 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002685 mHeavyWeightProcess.activities);
2686 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002687 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002688 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002689 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002690 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002691 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002692 null, "finish-heavy");
2693 }
2694 }
2695 }
2696
2697 mHeavyWeightProcess = null;
2698 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2699 }
2700 }
2701
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002702 public void crashApplication(int uid, int initialPid, String packageName,
2703 String message) {
2704 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2705 != PackageManager.PERMISSION_GRANTED) {
2706 String msg = "Permission Denial: crashApplication() from pid="
2707 + Binder.getCallingPid()
2708 + ", uid=" + Binder.getCallingUid()
2709 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2710 Slog.w(TAG, msg);
2711 throw new SecurityException(msg);
2712 }
2713
2714 synchronized(this) {
2715 ProcessRecord proc = null;
2716
2717 // Figure out which process to kill. We don't trust that initialPid
2718 // still has any relation to current pids, so must scan through the
2719 // list.
2720 synchronized (mPidsSelfLocked) {
2721 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2722 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002723 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002724 continue;
2725 }
2726 if (p.pid == initialPid) {
2727 proc = p;
2728 break;
2729 }
2730 for (String str : p.pkgList) {
2731 if (str.equals(packageName)) {
2732 proc = p;
2733 }
2734 }
2735 }
2736 }
2737
2738 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002739 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002740 + " initialPid=" + initialPid
2741 + " packageName=" + packageName);
2742 return;
2743 }
2744
2745 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002746 if (proc.pid == Process.myPid()) {
2747 Log.w(TAG, "crashApplication: trying to crash self!");
2748 return;
2749 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002750 long ident = Binder.clearCallingIdentity();
2751 try {
2752 proc.thread.scheduleCrash(message);
2753 } catch (RemoteException e) {
2754 }
2755 Binder.restoreCallingIdentity(ident);
2756 }
2757 }
2758 }
2759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 public final void finishSubActivity(IBinder token, String resultWho,
2761 int requestCode) {
2762 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002764 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 Binder.restoreCallingIdentity(origId);
2766 }
2767 }
2768
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002769 public boolean finishActivityAffinity(IBinder token) {
2770 synchronized(this) {
2771 final long origId = Binder.clearCallingIdentity();
2772 boolean res = mMainStack.finishActivityAffinityLocked(token);
2773 Binder.restoreCallingIdentity(origId);
2774 return res;
2775 }
2776 }
2777
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002778 public boolean willActivityBeVisible(IBinder token) {
2779 synchronized(this) {
2780 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002781 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2782 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002783 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002784 return true;
2785 }
2786 if (r.fullscreen && !r.finishing) {
2787 return false;
2788 }
2789 }
2790 return true;
2791 }
2792 }
2793
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002794 public void overridePendingTransition(IBinder token, String packageName,
2795 int enterAnim, int exitAnim) {
2796 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002797 ActivityRecord self = mMainStack.isInStackLocked(token);
2798 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002799 return;
2800 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002801
2802 final long origId = Binder.clearCallingIdentity();
2803
2804 if (self.state == ActivityState.RESUMED
2805 || self.state == ActivityState.PAUSING) {
2806 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002807 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002808 }
2809
2810 Binder.restoreCallingIdentity(origId);
2811 }
2812 }
2813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 * Main function for removing an existing process from the activity manager
2816 * as a result of that process going away. Clears out all connections
2817 * to the process.
2818 */
2819 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002820 boolean restarting, boolean allowRestart) {
2821 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002823 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 }
2825
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002826 if (mProfileProc == app) {
2827 clearProfilerLocked();
2828 }
2829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002831 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2832 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2833 mMainStack.mPausingActivity = null;
2834 }
2835 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2836 mMainStack.mLastPausedActivity = null;
2837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838
2839 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002840 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841
2842 boolean atTop = true;
2843 boolean hasVisibleActivities = false;
2844
2845 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002846 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002847 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 TAG, "Removing app " + app + " from history with " + i + " entries");
2849 while (i > 0) {
2850 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002851 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002852 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2854 if (r.app == app) {
2855 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002856 if (ActivityStack.DEBUG_ADD_REMOVE) {
2857 RuntimeException here = new RuntimeException("here");
2858 here.fillInStackTrace();
2859 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2860 + ": haveState=" + r.haveState
2861 + " stateNotNeeded=" + r.stateNotNeeded
2862 + " finishing=" + r.finishing
2863 + " state=" + r.state, here);
2864 }
2865 if (!r.finishing) {
2866 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002867 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2868 System.identityHashCode(r),
2869 r.task.taskId, r.shortComponentName,
2870 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002871 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002872 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873
2874 } else {
2875 // We have the current state for this activity, so
2876 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002877 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 TAG, "Keeping entry, setting app to null");
2879 if (r.visible) {
2880 hasVisibleActivities = true;
2881 }
2882 r.app = null;
2883 r.nowVisible = false;
2884 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002885 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2886 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 r.icicle = null;
2888 }
2889 }
2890
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002891 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 }
2893 atTop = false;
2894 }
2895
2896 app.activities.clear();
2897
2898 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002899 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 + " running instrumentation " + app.instrumentationClass);
2901 Bundle info = new Bundle();
2902 info.putString("shortMsg", "Process crashed.");
2903 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2904 }
2905
2906 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002907 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 // If there was nothing to resume, and we are not already
2909 // restarting this process, but there is a visible activity that
2910 // is hosted by the process... then make sure all visible
2911 // activities are running, taking care of restarting this
2912 // process.
2913 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002914 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 }
2916 }
2917 }
2918 }
2919
2920 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2921 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002923 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2924 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2926 return i;
2927 }
2928 }
2929 return -1;
2930 }
2931
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002932 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 IApplicationThread thread) {
2934 if (thread == null) {
2935 return null;
2936 }
2937
2938 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002939 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 }
2941
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002942 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 IApplicationThread thread) {
2944
2945 mProcDeaths[0]++;
2946
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002947 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2948 synchronized (stats) {
2949 stats.noteProcessDiedLocked(app.info.uid, pid);
2950 }
2951
Magnus Edlund7bb25812010-02-24 15:45:06 +01002952 // Clean up already done if the process has been re-started.
2953 if (app.pid == pid && app.thread != null &&
2954 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002955 if (!app.killedBackground) {
2956 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2957 + ") has died.");
2958 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002959 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002960 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 TAG, "Dying app: " + app + ", pid: " + pid
2962 + ", thread: " + thread.asBinder());
2963 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002964 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965
2966 if (doLowMem) {
2967 // If there are no longer any background processes running,
2968 // and the app that died was not running instrumentation,
2969 // then tell everyone we are now low on memory.
2970 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002971 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2972 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002973 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 haveBg = true;
2975 break;
2976 }
2977 }
2978
2979 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002980 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002981 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002982 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2983 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002984 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002985 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2986 // The low memory report is overriding any current
2987 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002988 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002989 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002990 rec.lastRequestedGc = 0;
2991 } else {
2992 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002994 rec.reportLowMemory = true;
2995 rec.lastLowMemory = now;
2996 mProcessesToGc.remove(rec);
2997 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 }
2999 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003000 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003001 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 }
3003 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003004 } else if (app.pid != pid) {
3005 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003006 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003007 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003008 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003009 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003010 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 + thread.asBinder());
3012 }
3013 }
3014
Dan Egnor42471dd2010-01-07 17:25:22 -08003015 /**
3016 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003017 * @param clearTraces causes the dump file to be erased prior to the new
3018 * traces being written, if true; when false, the new traces will be
3019 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003020 * @param firstPids of dalvik VM processes to dump stack traces for first
3021 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08003022 * @return file containing stack traces, or null if no dump file is configured
3023 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003024 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
3025 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003026 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3027 if (tracesPath == null || tracesPath.length() == 0) {
3028 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003030
3031 File tracesFile = new File(tracesPath);
3032 try {
3033 File tracesDir = tracesFile.getParentFile();
3034 if (!tracesDir.exists()) tracesFile.mkdirs();
3035 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3036
Christopher Tate6ee412d2010-05-28 12:01:56 -07003037 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003038 tracesFile.createNewFile();
3039 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3040 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003041 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003042 return null;
3043 }
3044
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003045 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
3046 return tracesFile;
3047 }
3048
3049 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
3050 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003051 // Use a FileObserver to detect when traces finish writing.
3052 // The order of traces is considered important to maintain for legibility.
3053 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3054 public synchronized void onEvent(int event, String path) { notify(); }
3055 };
3056
3057 try {
3058 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003059
3060 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003061 if (firstPids != null) {
3062 try {
3063 int num = firstPids.size();
3064 for (int i = 0; i < num; i++) {
3065 synchronized (observer) {
3066 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3067 observer.wait(200); // Wait for write-close, give up after 200msec
3068 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003069 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003070 } catch (InterruptedException e) {
3071 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003072 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003073 }
3074
3075 // Next measure CPU usage.
3076 if (processStats != null) {
3077 processStats.init();
3078 System.gc();
3079 processStats.update();
3080 try {
3081 synchronized (processStats) {
3082 processStats.wait(500); // measure over 1/2 second.
3083 }
3084 } catch (InterruptedException e) {
3085 }
3086 processStats.update();
3087
3088 // We'll take the stack crawls of just the top apps using CPU.
3089 final int N = processStats.countWorkingStats();
3090 int numProcs = 0;
3091 for (int i=0; i<N && numProcs<5; i++) {
3092 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3093 if (lastPids.indexOfKey(stats.pid) >= 0) {
3094 numProcs++;
3095 try {
3096 synchronized (observer) {
3097 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3098 observer.wait(200); // Wait for write-close, give up after 200msec
3099 }
3100 } catch (InterruptedException e) {
3101 Log.wtf(TAG, e);
3102 }
3103
3104 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003105 }
3106 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003107
Dan Egnor42471dd2010-01-07 17:25:22 -08003108 } finally {
3109 observer.stopWatching();
3110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 }
3112
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003113 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003114 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003115 return;
3116 }
3117 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3118 if (tracesPath == null || tracesPath.length() == 0) {
3119 return;
3120 }
3121
3122 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3123 StrictMode.allowThreadDiskWrites();
3124 try {
3125 final File tracesFile = new File(tracesPath);
3126 final File tracesDir = tracesFile.getParentFile();
3127 final File tracesTmp = new File(tracesDir, "__tmp__");
3128 try {
3129 if (!tracesDir.exists()) tracesFile.mkdirs();
3130 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3131
3132 if (tracesFile.exists()) {
3133 tracesTmp.delete();
3134 tracesFile.renameTo(tracesTmp);
3135 }
3136 StringBuilder sb = new StringBuilder();
3137 Time tobj = new Time();
3138 tobj.set(System.currentTimeMillis());
3139 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3140 sb.append(": ");
3141 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3142 sb.append(" since ");
3143 sb.append(msg);
3144 FileOutputStream fos = new FileOutputStream(tracesFile);
3145 fos.write(sb.toString().getBytes());
3146 if (app == null) {
3147 fos.write("\n*** No application process!".getBytes());
3148 }
3149 fos.close();
3150 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3151 } catch (IOException e) {
3152 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3153 return;
3154 }
3155
3156 if (app != null) {
3157 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3158 firstPids.add(app.pid);
3159 dumpStackTraces(tracesPath, firstPids, null, null);
3160 }
3161
3162 File lastTracesFile = null;
3163 File curTracesFile = null;
3164 for (int i=9; i>=0; i--) {
3165 String name = String.format("slow%02d.txt", i);
3166 curTracesFile = new File(tracesDir, name);
3167 if (curTracesFile.exists()) {
3168 if (lastTracesFile != null) {
3169 curTracesFile.renameTo(lastTracesFile);
3170 } else {
3171 curTracesFile.delete();
3172 }
3173 }
3174 lastTracesFile = curTracesFile;
3175 }
3176 tracesFile.renameTo(curTracesFile);
3177 if (tracesTmp.exists()) {
3178 tracesTmp.renameTo(tracesFile);
3179 }
3180 } finally {
3181 StrictMode.setThreadPolicy(oldPolicy);
3182 }
3183 }
3184
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003185 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3186 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003187 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3188 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3189
Dianne Hackborn287952c2010-09-22 22:34:31 -07003190 if (mController != null) {
3191 try {
3192 // 0 == continue, -1 = kill process immediately
3193 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3194 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3195 } catch (RemoteException e) {
3196 mController = null;
3197 }
3198 }
3199
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003200 long anrTime = SystemClock.uptimeMillis();
3201 if (MONITOR_CPU_USAGE) {
3202 updateCpuStatsNow();
3203 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003204
3205 synchronized (this) {
3206 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3207 if (mShuttingDown) {
3208 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3209 return;
3210 } else if (app.notResponding) {
3211 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3212 return;
3213 } else if (app.crashing) {
3214 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3215 return;
3216 }
3217
3218 // In case we come through here for the same app before completing
3219 // this one, mark as anring now so we will bail out.
3220 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003221
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003222 // Log the ANR to the event log.
3223 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3224 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003225
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003226 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003227 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003228
3229 int parentPid = app.pid;
3230 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003231 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003232
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003233 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003234
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003235 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3236 ProcessRecord r = mLruProcesses.get(i);
3237 if (r != null && r.thread != null) {
3238 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003239 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3240 if (r.persistent) {
3241 firstPids.add(pid);
3242 } else {
3243 lastPids.put(pid, Boolean.TRUE);
3244 }
3245 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 }
3248 }
3249
Dan Egnor42471dd2010-01-07 17:25:22 -08003250 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003251 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003252 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003253 info.append("ANR in ").append(app.processName);
3254 if (activity != null && activity.shortComponentName != null) {
3255 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003256 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003257 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003259 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003261 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003262 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264
Dianne Hackborn287952c2010-09-22 22:34:31 -07003265 final ProcessStats processStats = new ProcessStats(true);
3266
3267 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3268
Dan Egnor42471dd2010-01-07 17:25:22 -08003269 String cpuInfo = null;
3270 if (MONITOR_CPU_USAGE) {
3271 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003272 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003273 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003274 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003275 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003276 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 }
3278
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003279 info.append(processStats.printCurrentState(anrTime));
3280
Joe Onorato8a9b2202010-02-26 18:56:32 -08003281 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003282 if (tracesFile == null) {
3283 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3284 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3285 }
3286
Jeff Sharkeya353d262011-10-28 11:12:06 -07003287 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3288 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003289
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003290 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003292 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3293 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003295 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3296 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 }
3298 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003299 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 }
3301 }
3302
Dan Egnor42471dd2010-01-07 17:25:22 -08003303 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3304 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3305 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003306
3307 synchronized (this) {
3308 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003309 Slog.w(TAG, "Killing " + app + ": background ANR");
3310 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3311 app.processName, app.setAdj, "background ANR");
3312 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003313 return;
3314 }
3315
3316 // Set the app's notResponding state, and look up the errorReportReceiver
3317 makeAppNotRespondingLocked(app,
3318 activity != null ? activity.shortComponentName : null,
3319 annotation != null ? "ANR " + annotation : "ANR",
3320 info.toString());
3321
3322 // Bring up the infamous App Not Responding dialog
3323 Message msg = Message.obtain();
3324 HashMap map = new HashMap();
3325 msg.what = SHOW_NOT_RESPONDING_MSG;
3326 msg.obj = map;
3327 map.put("app", app);
3328 if (activity != null) {
3329 map.put("activity", activity);
3330 }
3331
3332 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 }
3335
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003336 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3337 if (!mLaunchWarningShown) {
3338 mLaunchWarningShown = true;
3339 mHandler.post(new Runnable() {
3340 @Override
3341 public void run() {
3342 synchronized (ActivityManagerService.this) {
3343 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3344 d.show();
3345 mHandler.postDelayed(new Runnable() {
3346 @Override
3347 public void run() {
3348 synchronized (ActivityManagerService.this) {
3349 d.dismiss();
3350 mLaunchWarningShown = false;
3351 }
3352 }
3353 }, 4000);
3354 }
3355 }
3356 });
3357 }
3358 }
3359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003361 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003362 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 int uid = Binder.getCallingUid();
3364 int pid = Binder.getCallingPid();
3365 long callingId = Binder.clearCallingIdentity();
3366 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003367 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 int pkgUid = -1;
3369 synchronized(this) {
3370 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003371 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 } catch (RemoteException e) {
3373 }
3374 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003375 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 return false;
3377 }
3378 if (uid == pkgUid || checkComponentPermission(
3379 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003380 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003382 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 } else {
3384 throw new SecurityException(pid+" does not have permission:"+
3385 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3386 "for process:"+packageName);
3387 }
3388 }
3389
3390 try {
3391 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003392 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3394 Uri.fromParts("package", packageName, null));
3395 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003396 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003397 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 } catch (RemoteException e) {
3399 }
3400 } finally {
3401 Binder.restoreCallingIdentity(callingId);
3402 }
3403 return true;
3404 }
3405
Dianne Hackborn03abb812010-01-04 18:43:19 -08003406 public void killBackgroundProcesses(final String packageName) {
3407 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3408 != PackageManager.PERMISSION_GRANTED &&
3409 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3410 != PackageManager.PERMISSION_GRANTED) {
3411 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 + Binder.getCallingPid()
3413 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003414 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003415 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 throw new SecurityException(msg);
3417 }
3418
Amith Yamasani483f3b02012-03-13 16:08:00 -07003419 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 long callingId = Binder.clearCallingIdentity();
3421 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003422 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003423 int pkgUid = -1;
3424 synchronized(this) {
3425 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003426 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 } catch (RemoteException e) {
3428 }
3429 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003430 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 return;
3432 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003433 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003434 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3435 }
3436 } finally {
3437 Binder.restoreCallingIdentity(callingId);
3438 }
3439 }
3440
3441 public void killAllBackgroundProcesses() {
3442 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3443 != PackageManager.PERMISSION_GRANTED) {
3444 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3445 + Binder.getCallingPid()
3446 + ", uid=" + Binder.getCallingUid()
3447 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3448 Slog.w(TAG, msg);
3449 throw new SecurityException(msg);
3450 }
3451
3452 long callingId = Binder.clearCallingIdentity();
3453 try {
3454 synchronized(this) {
3455 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3456 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3457 final int NA = apps.size();
3458 for (int ia=0; ia<NA; ia++) {
3459 ProcessRecord app = apps.valueAt(ia);
3460 if (app.persistent) {
3461 // we don't kill persistent processes
3462 continue;
3463 }
3464 if (app.removed) {
3465 procs.add(app);
3466 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3467 app.removed = true;
3468 procs.add(app);
3469 }
3470 }
3471 }
3472
3473 int N = procs.size();
3474 for (int i=0; i<N; i++) {
3475 removeProcessLocked(procs.get(i), false, true, "kill all background");
3476 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003477 }
3478 } finally {
3479 Binder.restoreCallingIdentity(callingId);
3480 }
3481 }
3482
3483 public void forceStopPackage(final String packageName) {
3484 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3485 != PackageManager.PERMISSION_GRANTED) {
3486 String msg = "Permission Denial: forceStopPackage() from pid="
3487 + Binder.getCallingPid()
3488 + ", uid=" + Binder.getCallingUid()
3489 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003490 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003491 throw new SecurityException(msg);
3492 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003493 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003494 long callingId = Binder.clearCallingIdentity();
3495 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003496 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003497 int pkgUid = -1;
3498 synchronized(this) {
3499 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003500 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003501 } catch (RemoteException e) {
3502 }
3503 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003504 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003505 return;
3506 }
3507 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003508 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003509 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003510 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003511 } catch (IllegalArgumentException e) {
3512 Slog.w(TAG, "Failed trying to unstop package "
3513 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 }
3516 } finally {
3517 Binder.restoreCallingIdentity(callingId);
3518 }
3519 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003520
3521 /*
3522 * The pkg name and uid have to be specified.
3523 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3524 */
3525 public void killApplicationWithUid(String pkg, int uid) {
3526 if (pkg == null) {
3527 return;
3528 }
3529 // Make sure the uid is valid.
3530 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003531 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003532 return;
3533 }
3534 int callerUid = Binder.getCallingUid();
3535 // Only the system server can kill an application
3536 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003537 // Post an aysnc message to kill the application
3538 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3539 msg.arg1 = uid;
3540 msg.arg2 = 0;
3541 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003542 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003543 } else {
3544 throw new SecurityException(callerUid + " cannot kill pkg: " +
3545 pkg);
3546 }
3547 }
3548
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003549 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003550 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003551
3552 final int uid = Binder.getCallingUid();
3553 final long origId = Binder.clearCallingIdentity();
3554 synchronized (this) {
3555 closeSystemDialogsLocked(uid, reason);
3556 }
3557 Binder.restoreCallingIdentity(origId);
3558 }
3559
3560 void closeSystemDialogsLocked(int callingUid, String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003561 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003562 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003563 if (reason != null) {
3564 intent.putExtra("reason", reason);
3565 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003566 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003567
Dianne Hackborne302a162012-05-15 14:58:32 -07003568 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3569 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborna3a041d2012-05-31 16:18:21 -07003570 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0
3571 && (r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLOSE_SYSTEM_DIALOGS) == 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003572 r.stack.finishActivityLocked(r, i,
3573 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003574 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003575 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003576
3577 broadcastIntentLocked(null, null, intent, null,
3578 null, 0, null, null, null, false, false, -1,
3579 callingUid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003580 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003581
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003582 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003583 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003584 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003585 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3586 for (int i=pids.length-1; i>=0; i--) {
3587 infos[i] = new Debug.MemoryInfo();
3588 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003589 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003590 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003591 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003592
Dianne Hackbornb437e092011-08-05 17:50:29 -07003593 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003594 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003595 long[] pss = new long[pids.length];
3596 for (int i=pids.length-1; i>=0; i--) {
3597 pss[i] = Debug.getPss(pids[i]);
3598 }
3599 return pss;
3600 }
3601
Christopher Tate5e1ab332009-09-01 20:32:49 -07003602 public void killApplicationProcess(String processName, int uid) {
3603 if (processName == null) {
3604 return;
3605 }
3606
3607 int callerUid = Binder.getCallingUid();
3608 // Only the system server can kill an application
3609 if (callerUid == Process.SYSTEM_UID) {
3610 synchronized (this) {
3611 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003612 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003613 try {
3614 app.thread.scheduleSuicide();
3615 } catch (RemoteException e) {
3616 // If the other end already died, then our work here is done.
3617 }
3618 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003619 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003620 + processName + " / " + uid);
3621 }
3622 }
3623 } else {
3624 throw new SecurityException(callerUid + " cannot kill app process: " +
3625 processName);
3626 }
3627 }
3628
Dianne Hackborn03abb812010-01-04 18:43:19 -08003629 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003630 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3632 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003633 if (!mProcessesReady) {
3634 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 intent.putExtra(Intent.EXTRA_UID, uid);
3637 broadcastIntentLocked(null, null, intent,
3638 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003639 false, false,
3640 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 }
3642
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003643 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003644 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003645 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003646 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647
Dianne Hackborn03abb812010-01-04 18:43:19 -08003648 // Remove all processes this package may have touched: all with the
3649 // same UID (except for the system or root user), and all whose name
3650 // matches the package name.
3651 final String procNamePrefix = packageName + ":";
3652 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3653 final int NA = apps.size();
3654 for (int ia=0; ia<NA; ia++) {
3655 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003656 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003657 // we don't kill persistent processes
3658 continue;
3659 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003660 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003661 if (doit) {
3662 procs.add(app);
3663 }
Amith Yamasani13593602012-03-22 16:16:17 -07003664 // If uid is specified and the uid and process name match
3665 // Or, the uid is not specified and the process name matches
3666 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003667 || ((app.processName.equals(packageName)
3668 || app.processName.startsWith(procNamePrefix))
3669 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003670 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003671 if (!doit) {
3672 return true;
3673 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003674 app.removed = true;
3675 procs.add(app);
3676 }
3677 }
3678 }
3679 }
3680
3681 int N = procs.size();
3682 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003683 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003684 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003685 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003686 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003687
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003688 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003689 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003690 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003691 int i;
3692 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 if (uid < 0) {
3695 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003696 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 } catch (RemoteException e) {
3698 }
3699 }
3700
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003701 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003702 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003703
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003704 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3705 while (badApps.hasNext()) {
3706 SparseArray<Long> ba = badApps.next();
3707 if (ba.get(uid) != null) {
3708 badApps.remove();
3709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 }
3711 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003712
3713 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003714 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003716 TaskRecord lastTask = null;
3717 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003718 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003719 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003720 if (r.userId == userId
3721 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003722 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003723 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003724 if (r.finishing) {
3725 // If this activity is just finishing, then it is not
3726 // interesting as far as something to stop.
3727 continue;
3728 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003729 return true;
3730 }
3731 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003732 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003733 if (samePackage) {
3734 if (r.app != null) {
3735 r.app.removed = true;
3736 }
3737 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003739 lastTask = r.task;
3740 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003741 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003742 i--;
3743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 }
3745 }
3746
3747 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003748 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003749 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003750 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003751 if (!doit) {
3752 return true;
3753 }
3754 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003755 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 if (service.app != null) {
3757 service.app.removed = true;
3758 }
3759 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003760 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 services.add(service);
3762 }
3763 }
3764
3765 N = services.size();
3766 for (i=0; i<N; i++) {
3767 bringDownServiceLocked(services.get(i), true);
3768 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003769
3770 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003771 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003772 if (provider.info.packageName.equals(name)
3773 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3774 if (!doit) {
3775 return true;
3776 }
3777 didSomething = true;
3778 providers.add(provider);
3779 }
3780 }
3781
3782 N = providers.size();
3783 for (i=0; i<N; i++) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003784 removeDyingProviderLocked(null, providers.get(i), true);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003785 }
3786
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003787 if (doit) {
3788 if (purgeCache) {
3789 AttributeCache ac = AttributeCache.instance();
3790 if (ac != null) {
3791 ac.removePackage(name);
3792 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003793 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003794 if (mBooted) {
3795 mMainStack.resumeTopActivityLocked(null);
3796 mMainStack.scheduleIdleLocked();
3797 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003798 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003799
3800 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 }
3802
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003803 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003804 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003806 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003807 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003808 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 + "/" + uid + ")");
3810
3811 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003812 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003813 if (mHeavyWeightProcess == app) {
3814 mHeavyWeightProcess = null;
3815 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 boolean needRestart = false;
3818 if (app.pid > 0 && app.pid != MY_PID) {
3819 int pid = app.pid;
3820 synchronized (mPidsSelfLocked) {
3821 mPidsSelfLocked.remove(pid);
3822 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3823 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003824 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003825 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003826 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003827 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003829 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003830 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003831 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 } else {
3833 needRestart = true;
3834 }
3835 }
3836 } else {
3837 mRemovedProcesses.add(app);
3838 }
3839
3840 return needRestart;
3841 }
3842
3843 private final void processStartTimedOutLocked(ProcessRecord app) {
3844 final int pid = app.pid;
3845 boolean gone = false;
3846 synchronized (mPidsSelfLocked) {
3847 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3848 if (knownApp != null && knownApp.thread == null) {
3849 mPidsSelfLocked.remove(pid);
3850 gone = true;
3851 }
3852 }
3853
3854 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003855 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003856 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003857 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003858 mProcessNames.remove(app.processName, app.uid);
3859 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003860 if (mHeavyWeightProcess == app) {
3861 mHeavyWeightProcess = null;
3862 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3863 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003864 // Take care of any launching providers waiting for this process.
3865 checkAppInLaunchingProvidersLocked(app, true);
3866 // Take care of any services that are waiting for the process.
3867 for (int i=0; i<mPendingServices.size(); i++) {
3868 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003869 if ((app.uid == sr.appInfo.uid
3870 && app.processName.equals(sr.processName))
3871 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003872 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003873 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003874 mPendingServices.remove(i);
3875 i--;
3876 bringDownServiceLocked(sr, true);
3877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003879 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3880 app.processName, app.setAdj, "start timeout");
3881 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003882 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003883 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003884 try {
3885 IBackupManager bm = IBackupManager.Stub.asInterface(
3886 ServiceManager.getService(Context.BACKUP_SERVICE));
3887 bm.agentDisconnected(app.info.packageName);
3888 } catch (RemoteException e) {
3889 // Can't happen; the backup manager is local
3890 }
3891 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003892 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003893 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003894 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003897 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 }
3899 }
3900
3901 private final boolean attachApplicationLocked(IApplicationThread thread,
3902 int pid) {
3903
3904 // Find the application record that is being attached... either via
3905 // the pid if we are running in multiple processes, or just pull the
3906 // next app record if we are emulating process with anonymous threads.
3907 ProcessRecord app;
3908 if (pid != MY_PID && pid >= 0) {
3909 synchronized (mPidsSelfLocked) {
3910 app = mPidsSelfLocked.get(pid);
3911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 } else {
3913 app = null;
3914 }
3915
3916 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003917 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003919 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003921 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 } else {
3923 try {
3924 thread.scheduleExit();
3925 } catch (Exception e) {
3926 // Ignore exceptions.
3927 }
3928 }
3929 return false;
3930 }
3931
3932 // If this application record is still attached to a previous
3933 // process, clean it up now.
3934 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003935 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 }
3937
3938 // Tell the process all about itself.
3939
Joe Onorato8a9b2202010-02-26 18:56:32 -08003940 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 TAG, "Binding process pid " + pid + " to record " + app);
3942
3943 String processName = app.processName;
3944 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003945 AppDeathRecipient adr = new AppDeathRecipient(
3946 app, pid, thread);
3947 thread.asBinder().linkToDeath(adr, 0);
3948 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 } catch (RemoteException e) {
3950 app.resetPackageList();
3951 startProcessLocked(app, "link fail", processName);
3952 return false;
3953 }
3954
Doug Zongker2bec3d42009-12-04 12:52:44 -08003955 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956
3957 app.thread = thread;
3958 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003959 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3960 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 app.forcingToForeground = null;
3962 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003963 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 app.debugging = false;
3965
3966 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3967
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003968 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003969 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003971 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003972 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003973 }
3974
Joe Onorato8a9b2202010-02-26 18:56:32 -08003975 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003976 TAG, "New app record " + app
3977 + " thread=" + thread.asBinder() + " pid=" + pid);
3978 try {
3979 int testMode = IApplicationThread.DEBUG_OFF;
3980 if (mDebugApp != null && mDebugApp.equals(processName)) {
3981 testMode = mWaitForDebugger
3982 ? IApplicationThread.DEBUG_WAIT
3983 : IApplicationThread.DEBUG_ON;
3984 app.debugging = true;
3985 if (mDebugTransient) {
3986 mDebugApp = mOrigDebugApp;
3987 mWaitForDebugger = mOrigWaitForDebugger;
3988 }
3989 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003990 String profileFile = app.instrumentationProfileFile;
3991 ParcelFileDescriptor profileFd = null;
3992 boolean profileAutoStop = false;
3993 if (mProfileApp != null && mProfileApp.equals(processName)) {
3994 mProfileProc = app;
3995 profileFile = mProfileFile;
3996 profileFd = mProfileFd;
3997 profileAutoStop = mAutoStopProfiler;
3998 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003999 boolean enableOpenGlTrace = false;
4000 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4001 enableOpenGlTrace = true;
4002 mOpenGlTraceApp = null;
4003 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004004
Christopher Tate181fafa2009-05-14 11:12:14 -07004005 // If the app is being launched for restore or full backup, set it up specially
4006 boolean isRestrictedBackupMode = false;
4007 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4008 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004009 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004010 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4011 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004012
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004013 ensurePackageDexOpt(app.instrumentationInfo != null
4014 ? app.instrumentationInfo.packageName
4015 : app.info.packageName);
4016 if (app.instrumentationClass != null) {
4017 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004018 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004019 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004020 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004021 ApplicationInfo appInfo = app.instrumentationInfo != null
4022 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004023 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004024 if (profileFd != null) {
4025 profileFd = profileFd.dup();
4026 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004027 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004028 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004029 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4030 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004031 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004032 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004033 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004034 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 } catch (Exception e) {
4036 // todo: Yikes! What should we do? For now we will try to
4037 // start another process, but that could easily get us in
4038 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004039 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040
4041 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004042 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 startProcessLocked(app, "bind fail", processName);
4044 return false;
4045 }
4046
4047 // Remove this record from the list of starting applications.
4048 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004049 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4050 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 mProcessesOnHold.remove(app);
4052
4053 boolean badApp = false;
4054 boolean didSomething = false;
4055
4056 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004057 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004058 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004059 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 && processName.equals(hr.processName)) {
4061 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004062 if (mHeadless) {
4063 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4064 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 didSomething = true;
4066 }
4067 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004068 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004069 + hr.intent.getComponent().flattenToShortString(), e);
4070 badApp = true;
4071 }
4072 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004073 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 }
4075 }
4076
4077 // Find any services that should be running in this process...
4078 if (!badApp && mPendingServices.size() > 0) {
4079 ServiceRecord sr = null;
4080 try {
4081 for (int i=0; i<mPendingServices.size(); i++) {
4082 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004083 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4084 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 continue;
4086 }
4087
4088 mPendingServices.remove(i);
4089 i--;
4090 realStartServiceLocked(sr, app);
4091 didSomething = true;
4092 }
4093 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004094 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 + sr.shortName, e);
4096 badApp = true;
4097 }
4098 }
4099
Christopher Tatef46723b2012-01-26 14:19:24 -08004100 // Check if a next-broadcast receiver is in this process...
4101 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004103 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004105 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 }
4108 }
4109
Christopher Tate181fafa2009-05-14 11:12:14 -07004110 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004111 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004112 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004113 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004114 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004115 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4116 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4117 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004118 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004119 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004120 e.printStackTrace();
4121 }
4122 }
4123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 if (badApp) {
4125 // todo: Also need to kill application to deal with all
4126 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004127 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 return false;
4129 }
4130
4131 if (!didSomething) {
4132 updateOomAdjLocked();
4133 }
4134
4135 return true;
4136 }
4137
4138 public final void attachApplication(IApplicationThread thread) {
4139 synchronized (this) {
4140 int callingPid = Binder.getCallingPid();
4141 final long origId = Binder.clearCallingIdentity();
4142 attachApplicationLocked(thread, callingPid);
4143 Binder.restoreCallingIdentity(origId);
4144 }
4145 }
4146
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004147 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004149 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4150 if (stopProfiling) {
4151 synchronized (this) {
4152 if (mProfileProc == r.app) {
4153 if (mProfileFd != null) {
4154 try {
4155 mProfileFd.close();
4156 } catch (IOException e) {
4157 }
4158 clearProfilerLocked();
4159 }
4160 }
4161 }
4162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163 Binder.restoreCallingIdentity(origId);
4164 }
4165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004167 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004168 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004170
4171 synchronized (this) {
4172 updateEventDispatchingLocked();
4173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 }
4175
Dianne Hackborn661cd522011-08-22 00:26:20 -07004176 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004177 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004178 mWindowManager.showBootMessage(msg, always);
4179 }
4180
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004181 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004182 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004183 final long token = Binder.clearCallingIdentity();
4184 try {
4185 synchronized (this) {
4186 if (mLockScreenShown) {
4187 mLockScreenShown = false;
4188 comeOutOfSleepIfNeededLocked();
4189 }
4190 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004191 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004192 } finally {
4193 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004194 }
4195 }
4196
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004197 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004198 IntentFilter pkgFilter = new IntentFilter();
4199 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4200 pkgFilter.addDataScheme("package");
4201 mContext.registerReceiver(new BroadcastReceiver() {
4202 @Override
4203 public void onReceive(Context context, Intent intent) {
4204 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4205 if (pkgs != null) {
4206 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004207 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004208 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4209 setResultCode(Activity.RESULT_OK);
4210 return;
4211 }
4212 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004213 }
4214 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004215 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004216 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004217
4218 IntentFilter userFilter = new IntentFilter();
4219 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4220 mContext.registerReceiver(new BroadcastReceiver() {
4221 @Override
4222 public void onReceive(Context context, Intent intent) {
4223 onUserRemoved(intent);
4224 }
4225 }, userFilter);
4226
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004227 synchronized (this) {
4228 // Ensure that any processes we had put on hold are now started
4229 // up.
4230 final int NP = mProcessesOnHold.size();
4231 if (NP > 0) {
4232 ArrayList<ProcessRecord> procs =
4233 new ArrayList<ProcessRecord>(mProcessesOnHold);
4234 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004235 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4236 + procs.get(ip));
4237 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004238 }
4239 }
4240
4241 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004242 // Start looking for apps that are abusing wake locks.
4243 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004244 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004245 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004246 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004247 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004248 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004249 broadcastIntentLocked(null, null,
4250 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4251 null, null, 0, null, null,
4252 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004253 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004254 }
4255 }
4256 }
4257
4258 final void ensureBootCompleted() {
4259 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004260 boolean enableScreen;
4261 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004262 booting = mBooting;
4263 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004264 enableScreen = !mBooted;
4265 mBooted = true;
4266 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004267
4268 if (booting) {
4269 finishBooting();
4270 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004271
4272 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004273 enableScreenAfterBoot();
4274 }
4275 }
4276
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004277 public final void activityPaused(IBinder token) {
4278 final long origId = Binder.clearCallingIdentity();
4279 mMainStack.activityPaused(token, false);
4280 Binder.restoreCallingIdentity(origId);
4281 }
4282
4283 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4284 CharSequence description) {
4285 if (localLOGV) Slog.v(
4286 TAG, "Activity stopped: token=" + token);
4287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 // Refuse possible leaked file descriptors
4289 if (icicle != null && icicle.hasFileDescriptors()) {
4290 throw new IllegalArgumentException("File descriptors passed in Bundle");
4291 }
4292
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004293 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294
4295 final long origId = Binder.clearCallingIdentity();
4296
4297 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004298 r = mMainStack.isInStackLocked(token);
4299 if (r != null) {
4300 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 }
4302 }
4303
4304 if (r != null) {
4305 sendPendingThumbnail(r, null, null, null, false);
4306 }
4307
4308 trimApplications();
4309
4310 Binder.restoreCallingIdentity(origId);
4311 }
4312
4313 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004314 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004315 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 }
4317
4318 public String getCallingPackage(IBinder token) {
4319 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004320 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004321 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 }
4323 }
4324
4325 public ComponentName getCallingActivity(IBinder token) {
4326 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004327 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 return r != null ? r.intent.getComponent() : null;
4329 }
4330 }
4331
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004332 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004333 ActivityRecord r = mMainStack.isInStackLocked(token);
4334 if (r == null) {
4335 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004337 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 }
4339
4340 public ComponentName getActivityClassForToken(IBinder token) {
4341 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004342 ActivityRecord r = mMainStack.isInStackLocked(token);
4343 if (r == null) {
4344 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004346 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 }
4348 }
4349
4350 public String getPackageForToken(IBinder token) {
4351 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004352 ActivityRecord r = mMainStack.isInStackLocked(token);
4353 if (r == null) {
4354 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004355 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004356 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 }
4358 }
4359
4360 public IIntentSender getIntentSender(int type,
4361 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004362 int requestCode, Intent[] intents, String[] resolvedTypes,
4363 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004364 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004366 if (intents != null) {
4367 if (intents.length < 1) {
4368 throw new IllegalArgumentException("Intents array length must be >= 1");
4369 }
4370 for (int i=0; i<intents.length; i++) {
4371 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004372 if (intent != null) {
4373 if (intent.hasFileDescriptors()) {
4374 throw new IllegalArgumentException("File descriptors passed in Intent");
4375 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004376 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004377 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4378 throw new IllegalArgumentException(
4379 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4380 }
4381 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004382 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004383 }
4384 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004385 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004386 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004387 }
4388 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004389 if (options != null) {
4390 if (options.hasFileDescriptors()) {
4391 throw new IllegalArgumentException("File descriptors passed in options");
4392 }
4393 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004395 synchronized(this) {
4396 int callingUid = Binder.getCallingUid();
4397 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004398 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004399 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004400 .getPackageUid(packageName, UserId.getUserId(callingUid));
4401 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 String msg = "Permission Denial: getIntentSender() from pid="
4403 + Binder.getCallingPid()
4404 + ", uid=" + Binder.getCallingUid()
4405 + ", (need uid=" + uid + ")"
4406 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004407 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004408 throw new SecurityException(msg);
4409 }
4410 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004411
Amith Yamasani742a6712011-05-04 14:49:28 -07004412 if (DEBUG_MU)
4413 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4414 + Binder.getOrigCallingUid());
4415 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004416 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004418 } catch (RemoteException e) {
4419 throw new SecurityException(e);
4420 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004421 }
4422 }
4423
4424 IIntentSender getIntentSenderLocked(int type,
4425 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004426 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4427 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004428 if (DEBUG_MU)
4429 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004430 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004431 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004432 activity = mMainStack.isInStackLocked(token);
4433 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004434 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004435 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004436 if (activity.finishing) {
4437 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004438 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004439 }
4440
4441 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4442 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4443 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4444 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4445 |PendingIntent.FLAG_UPDATE_CURRENT);
4446
4447 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4448 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004449 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004450 WeakReference<PendingIntentRecord> ref;
4451 ref = mIntentSenderRecords.get(key);
4452 PendingIntentRecord rec = ref != null ? ref.get() : null;
4453 if (rec != null) {
4454 if (!cancelCurrent) {
4455 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004456 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004457 rec.key.requestIntent.replaceExtras(intents != null ?
4458 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004459 }
4460 if (intents != null) {
4461 intents[intents.length-1] = rec.key.requestIntent;
4462 rec.key.allIntents = intents;
4463 rec.key.allResolvedTypes = resolvedTypes;
4464 } else {
4465 rec.key.allIntents = null;
4466 rec.key.allResolvedTypes = null;
4467 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 return rec;
4470 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004471 rec.canceled = true;
4472 mIntentSenderRecords.remove(key);
4473 }
4474 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475 return rec;
4476 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004477 rec = new PendingIntentRecord(this, key, callingUid);
4478 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004479 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004480 if (activity.pendingResults == null) {
4481 activity.pendingResults
4482 = new HashSet<WeakReference<PendingIntentRecord>>();
4483 }
4484 activity.pendingResults.add(rec.ref);
4485 }
4486 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 }
4488
4489 public void cancelIntentSender(IIntentSender sender) {
4490 if (!(sender instanceof PendingIntentRecord)) {
4491 return;
4492 }
4493 synchronized(this) {
4494 PendingIntentRecord rec = (PendingIntentRecord)sender;
4495 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004496 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004497 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004498 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499 String msg = "Permission Denial: cancelIntentSender() from pid="
4500 + Binder.getCallingPid()
4501 + ", uid=" + Binder.getCallingUid()
4502 + " is not allowed to cancel packges "
4503 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004504 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 throw new SecurityException(msg);
4506 }
4507 } catch (RemoteException e) {
4508 throw new SecurityException(e);
4509 }
4510 cancelIntentSenderLocked(rec, true);
4511 }
4512 }
4513
4514 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4515 rec.canceled = true;
4516 mIntentSenderRecords.remove(rec.key);
4517 if (cleanActivity && rec.key.activity != null) {
4518 rec.key.activity.pendingResults.remove(rec.ref);
4519 }
4520 }
4521
4522 public String getPackageForIntentSender(IIntentSender pendingResult) {
4523 if (!(pendingResult instanceof PendingIntentRecord)) {
4524 return null;
4525 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004526 try {
4527 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4528 return res.key.packageName;
4529 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 }
4531 return null;
4532 }
4533
Christopher Tatec4a07d12012-04-06 14:19:13 -07004534 public int getUidForIntentSender(IIntentSender sender) {
4535 if (sender instanceof PendingIntentRecord) {
4536 try {
4537 PendingIntentRecord res = (PendingIntentRecord)sender;
4538 return res.uid;
4539 } catch (ClassCastException e) {
4540 }
4541 }
4542 return -1;
4543 }
4544
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004545 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4546 if (!(pendingResult instanceof PendingIntentRecord)) {
4547 return false;
4548 }
4549 try {
4550 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4551 if (res.key.allIntents == null) {
4552 return false;
4553 }
4554 for (int i=0; i<res.key.allIntents.length; i++) {
4555 Intent intent = res.key.allIntents[i];
4556 if (intent.getPackage() != null && intent.getComponent() != null) {
4557 return false;
4558 }
4559 }
4560 return true;
4561 } catch (ClassCastException e) {
4562 }
4563 return false;
4564 }
4565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 public void setProcessLimit(int max) {
4567 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4568 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004569 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004570 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004571 mProcessLimitOverride = max;
4572 }
4573 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004574 }
4575
4576 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004577 synchronized (this) {
4578 return mProcessLimitOverride;
4579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580 }
4581
4582 void foregroundTokenDied(ForegroundToken token) {
4583 synchronized (ActivityManagerService.this) {
4584 synchronized (mPidsSelfLocked) {
4585 ForegroundToken cur
4586 = mForegroundProcesses.get(token.pid);
4587 if (cur != token) {
4588 return;
4589 }
4590 mForegroundProcesses.remove(token.pid);
4591 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4592 if (pr == null) {
4593 return;
4594 }
4595 pr.forcingToForeground = null;
4596 pr.foregroundServices = false;
4597 }
4598 updateOomAdjLocked();
4599 }
4600 }
4601
4602 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4603 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4604 "setProcessForeground()");
4605 synchronized(this) {
4606 boolean changed = false;
4607
4608 synchronized (mPidsSelfLocked) {
4609 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004610 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004611 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612 return;
4613 }
4614 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4615 if (oldToken != null) {
4616 oldToken.token.unlinkToDeath(oldToken, 0);
4617 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004618 if (pr != null) {
4619 pr.forcingToForeground = null;
4620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 changed = true;
4622 }
4623 if (isForeground && token != null) {
4624 ForegroundToken newToken = new ForegroundToken() {
4625 public void binderDied() {
4626 foregroundTokenDied(this);
4627 }
4628 };
4629 newToken.pid = pid;
4630 newToken.token = token;
4631 try {
4632 token.linkToDeath(newToken, 0);
4633 mForegroundProcesses.put(pid, newToken);
4634 pr.forcingToForeground = token;
4635 changed = true;
4636 } catch (RemoteException e) {
4637 // If the process died while doing this, we will later
4638 // do the cleanup with the process death link.
4639 }
4640 }
4641 }
4642
4643 if (changed) {
4644 updateOomAdjLocked();
4645 }
4646 }
4647 }
4648
4649 // =========================================================
4650 // PERMISSIONS
4651 // =========================================================
4652
4653 static class PermissionController extends IPermissionController.Stub {
4654 ActivityManagerService mActivityManagerService;
4655 PermissionController(ActivityManagerService activityManagerService) {
4656 mActivityManagerService = activityManagerService;
4657 }
4658
4659 public boolean checkPermission(String permission, int pid, int uid) {
4660 return mActivityManagerService.checkPermission(permission, pid,
4661 uid) == PackageManager.PERMISSION_GRANTED;
4662 }
4663 }
4664
4665 /**
4666 * This can be called with or without the global lock held.
4667 */
4668 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004669 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004670 // We might be performing an operation on behalf of an indirect binder
4671 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4672 // client identity accordingly before proceeding.
4673 Identity tlsIdentity = sCallerIdentity.get();
4674 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004675 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004676 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4677 uid = tlsIdentity.uid;
4678 pid = tlsIdentity.pid;
4679 }
4680
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004681 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 return PackageManager.PERMISSION_GRANTED;
4683 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004684
4685 return ActivityManager.checkComponentPermission(permission, uid,
4686 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 }
4688
4689 /**
4690 * As the only public entry point for permissions checking, this method
4691 * can enforce the semantic that requesting a check on a null global
4692 * permission is automatically denied. (Internally a null permission
4693 * string is used when calling {@link #checkComponentPermission} in cases
4694 * when only uid-based security is needed.)
4695 *
4696 * This can be called with or without the global lock held.
4697 */
4698 public int checkPermission(String permission, int pid, int uid) {
4699 if (permission == null) {
4700 return PackageManager.PERMISSION_DENIED;
4701 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004702 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004703 }
4704
4705 /**
4706 * Binder IPC calls go through the public entry point.
4707 * This can be called with or without the global lock held.
4708 */
4709 int checkCallingPermission(String permission) {
4710 return checkPermission(permission,
4711 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004712 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004713 }
4714
4715 /**
4716 * This can be called with or without the global lock held.
4717 */
4718 void enforceCallingPermission(String permission, String func) {
4719 if (checkCallingPermission(permission)
4720 == PackageManager.PERMISSION_GRANTED) {
4721 return;
4722 }
4723
4724 String msg = "Permission Denial: " + func + " from pid="
4725 + Binder.getCallingPid()
4726 + ", uid=" + Binder.getCallingUid()
4727 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004728 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 throw new SecurityException(msg);
4730 }
4731
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004732 /**
4733 * Determine if UID is holding permissions required to access {@link Uri} in
4734 * the given {@link ProviderInfo}. Final permission checking is always done
4735 * in {@link ContentProvider}.
4736 */
4737 private final boolean checkHoldingPermissionsLocked(
4738 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004739 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4740 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004741
4742 if (pi.applicationInfo.uid == uid) {
4743 return true;
4744 } else if (!pi.exported) {
4745 return false;
4746 }
4747
4748 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4749 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004750 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004751 // check if target holds top-level <provider> permissions
4752 if (!readMet && pi.readPermission != null
4753 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4754 readMet = true;
4755 }
4756 if (!writeMet && pi.writePermission != null
4757 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4758 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004759 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004760
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004761 // track if unprotected read/write is allowed; any denied
4762 // <path-permission> below removes this ability
4763 boolean allowDefaultRead = pi.readPermission == null;
4764 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004765
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004766 // check if target holds any <path-permission> that match uri
4767 final PathPermission[] pps = pi.pathPermissions;
4768 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004769 final String path = uri.getPath();
4770 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004771 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004772 i--;
4773 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004774 if (pp.match(path)) {
4775 if (!readMet) {
4776 final String pprperm = pp.getReadPermission();
4777 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4778 + pprperm + " for " + pp.getPath()
4779 + ": match=" + pp.match(path)
4780 + " check=" + pm.checkUidPermission(pprperm, uid));
4781 if (pprperm != null) {
4782 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4783 readMet = true;
4784 } else {
4785 allowDefaultRead = false;
4786 }
4787 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004788 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004789 if (!writeMet) {
4790 final String ppwperm = pp.getWritePermission();
4791 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4792 + ppwperm + " for " + pp.getPath()
4793 + ": match=" + pp.match(path)
4794 + " check=" + pm.checkUidPermission(ppwperm, uid));
4795 if (ppwperm != null) {
4796 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4797 writeMet = true;
4798 } else {
4799 allowDefaultWrite = false;
4800 }
4801 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004802 }
4803 }
4804 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004805 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004806
4807 // grant unprotected <provider> read/write, if not blocked by
4808 // <path-permission> above
4809 if (allowDefaultRead) readMet = true;
4810 if (allowDefaultWrite) writeMet = true;
4811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 } catch (RemoteException e) {
4813 return false;
4814 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004815
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004816 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004817 }
4818
4819 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4820 int modeFlags) {
4821 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004822 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004823 return true;
4824 }
4825 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4826 if (perms == null) return false;
4827 UriPermission perm = perms.get(uri);
4828 if (perm == null) return false;
4829 return (modeFlags&perm.modeFlags) == modeFlags;
4830 }
4831
4832 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004833 enforceNotIsolatedCaller("checkUriPermission");
4834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004835 // Another redirected-binder-call permissions check as in
4836 // {@link checkComponentPermission}.
4837 Identity tlsIdentity = sCallerIdentity.get();
4838 if (tlsIdentity != null) {
4839 uid = tlsIdentity.uid;
4840 pid = tlsIdentity.pid;
4841 }
4842
Amith Yamasani742a6712011-05-04 14:49:28 -07004843 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004844 // Our own process gets to do everything.
4845 if (pid == MY_PID) {
4846 return PackageManager.PERMISSION_GRANTED;
4847 }
4848 synchronized(this) {
4849 return checkUriPermissionLocked(uri, uid, modeFlags)
4850 ? PackageManager.PERMISSION_GRANTED
4851 : PackageManager.PERMISSION_DENIED;
4852 }
4853 }
4854
Dianne Hackborn39792d22010-08-19 18:01:52 -07004855 /**
4856 * Check if the targetPkg can be granted permission to access uri by
4857 * the callingUid using the given modeFlags. Throws a security exception
4858 * if callingUid is not allowed to do this. Returns the uid of the target
4859 * if the URI permission grant should be performed; returns -1 if it is not
4860 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004861 * If you already know the uid of the target, you can supply it in
4862 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004863 */
4864 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004865 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004866 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4867 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4868 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004869 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004870 }
4871
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004872 if (targetPkg != null) {
4873 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4874 "Checking grant " + targetPkg + " permission to " + uri);
4875 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004876
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004877 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004878
4879 // If this is not a content: uri, we can't do anything with it.
4880 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004881 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004882 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004883 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 }
4885
4886 String name = uri.getAuthority();
4887 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004888 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4889 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890 if (cpr != null) {
4891 pi = cpr.info;
4892 } else {
4893 try {
4894 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004895 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004896 } catch (RemoteException ex) {
4897 }
4898 }
4899 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004900 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004901 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 }
4903
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004904 int targetUid = lastTargetUid;
4905 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004906 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004907 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004908 if (targetUid < 0) {
4909 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4910 "Can't grant URI permission no uid for: " + targetPkg);
4911 return -1;
4912 }
4913 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004914 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004916 }
4917
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004918 if (targetUid >= 0) {
4919 // First... does the target actually need this permission?
4920 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4921 // No need to grant the target this permission.
4922 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4923 "Target " + targetPkg + " already has full permission to " + uri);
4924 return -1;
4925 }
4926 } else {
4927 // First... there is no target package, so can anyone access it?
4928 boolean allowed = pi.exported;
4929 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4930 if (pi.readPermission != null) {
4931 allowed = false;
4932 }
4933 }
4934 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4935 if (pi.writePermission != null) {
4936 allowed = false;
4937 }
4938 }
4939 if (allowed) {
4940 return -1;
4941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004942 }
4943
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004944 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004945 if (!pi.grantUriPermissions) {
4946 throw new SecurityException("Provider " + pi.packageName
4947 + "/" + pi.name
4948 + " does not allow granting of Uri permissions (uri "
4949 + uri + ")");
4950 }
4951 if (pi.uriPermissionPatterns != null) {
4952 final int N = pi.uriPermissionPatterns.length;
4953 boolean allowed = false;
4954 for (int i=0; i<N; i++) {
4955 if (pi.uriPermissionPatterns[i] != null
4956 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4957 allowed = true;
4958 break;
4959 }
4960 }
4961 if (!allowed) {
4962 throw new SecurityException("Provider " + pi.packageName
4963 + "/" + pi.name
4964 + " does not allow granting of permission to path of Uri "
4965 + uri);
4966 }
4967 }
4968
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004969 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004970 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004971 if (callingUid != Process.myUid()) {
4972 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4973 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4974 throw new SecurityException("Uid " + callingUid
4975 + " does not have permission to uri " + uri);
4976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004977 }
4978 }
4979
Dianne Hackborn39792d22010-08-19 18:01:52 -07004980 return targetUid;
4981 }
4982
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004983 public int checkGrantUriPermission(int callingUid, String targetPkg,
4984 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004985 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004986 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004987 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004988 }
4989 }
4990
Dianne Hackborn39792d22010-08-19 18:01:52 -07004991 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4992 Uri uri, int modeFlags, UriPermissionOwner owner) {
4993 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4994 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4995 if (modeFlags == 0) {
4996 return;
4997 }
4998
4999 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 // to the uri, and the target doesn't. Let's now give this to
5001 // the target.
5002
Joe Onorato8a9b2202010-02-26 18:56:32 -08005003 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005004 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005006 HashMap<Uri, UriPermission> targetUris
5007 = mGrantedUriPermissions.get(targetUid);
5008 if (targetUris == null) {
5009 targetUris = new HashMap<Uri, UriPermission>();
5010 mGrantedUriPermissions.put(targetUid, targetUris);
5011 }
5012
5013 UriPermission perm = targetUris.get(uri);
5014 if (perm == null) {
5015 perm = new UriPermission(targetUid, uri);
5016 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005017 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005019 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005020 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005021 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005022 } else {
5023 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5024 perm.readOwners.add(owner);
5025 owner.addReadPermission(perm);
5026 }
5027 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5028 perm.writeOwners.add(owner);
5029 owner.addWritePermission(perm);
5030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005031 }
5032 }
5033
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005034 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5035 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005036 if (targetPkg == null) {
5037 throw new NullPointerException("targetPkg");
5038 }
5039
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005040 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005041 if (targetUid < 0) {
5042 return;
5043 }
5044
5045 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5046 }
5047
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005048 static class NeededUriGrants extends ArrayList<Uri> {
5049 final String targetPkg;
5050 final int targetUid;
5051 final int flags;
5052
5053 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5054 targetPkg = _targetPkg;
5055 targetUid = _targetUid;
5056 flags = _flags;
5057 }
5058 }
5059
Dianne Hackborn39792d22010-08-19 18:01:52 -07005060 /**
5061 * Like checkGrantUriPermissionLocked, but takes an Intent.
5062 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005063 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5064 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005065 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005066 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5067 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005068 + " from " + intent + "; flags=0x"
5069 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5070
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005071 if (targetPkg == null) {
5072 throw new NullPointerException("targetPkg");
5073 }
5074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005075 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005076 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005077 }
5078 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005079 ClipData clip = intent.getClipData();
5080 if (data == null && clip == null) {
5081 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005082 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005083 if (data != null) {
5084 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5085 mode, needed != null ? needed.targetUid : -1);
5086 if (target > 0) {
5087 if (needed == null) {
5088 needed = new NeededUriGrants(targetPkg, target, mode);
5089 }
5090 needed.add(data);
5091 }
5092 }
5093 if (clip != null) {
5094 for (int i=0; i<clip.getItemCount(); i++) {
5095 Uri uri = clip.getItemAt(i).getUri();
5096 if (uri != null) {
5097 int target = -1;
5098 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5099 mode, needed != null ? needed.targetUid : -1);
5100 if (target > 0) {
5101 if (needed == null) {
5102 needed = new NeededUriGrants(targetPkg, target, mode);
5103 }
5104 needed.add(uri);
5105 }
5106 } else {
5107 Intent clipIntent = clip.getItemAt(i).getIntent();
5108 if (clipIntent != null) {
5109 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5110 callingUid, targetPkg, clipIntent, mode, needed);
5111 if (newNeeded != null) {
5112 needed = newNeeded;
5113 }
5114 }
5115 }
5116 }
5117 }
5118
5119 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005120 }
5121
5122 /**
5123 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5124 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005125 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5126 UriPermissionOwner owner) {
5127 if (needed != null) {
5128 for (int i=0; i<needed.size(); i++) {
5129 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5130 needed.get(i), needed.flags, owner);
5131 }
5132 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005133 }
5134
5135 void grantUriPermissionFromIntentLocked(int callingUid,
5136 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005137 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005138 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005139 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005140 return;
5141 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005142
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005143 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144 }
5145
5146 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5147 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005148 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005149 synchronized(this) {
5150 final ProcessRecord r = getRecordForAppLocked(caller);
5151 if (r == null) {
5152 throw new SecurityException("Unable to find app for caller "
5153 + caller
5154 + " when granting permission to uri " + uri);
5155 }
5156 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005157 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005158 }
5159 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005160 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005161 }
5162
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005163 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005164 null);
5165 }
5166 }
5167
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005168 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005169 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5170 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5171 HashMap<Uri, UriPermission> perms
5172 = mGrantedUriPermissions.get(perm.uid);
5173 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005174 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005175 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005176 perms.remove(perm.uri);
5177 if (perms.size() == 0) {
5178 mGrantedUriPermissions.remove(perm.uid);
5179 }
5180 }
5181 }
5182 }
5183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005184 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5185 int modeFlags) {
5186 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5187 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5188 if (modeFlags == 0) {
5189 return;
5190 }
5191
Joe Onorato8a9b2202010-02-26 18:56:32 -08005192 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005193 "Revoking all granted permissions to " + uri);
5194
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005195 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196
5197 final String authority = uri.getAuthority();
5198 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005199 int userId = UserId.getUserId(callingUid);
5200 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005201 if (cpr != null) {
5202 pi = cpr.info;
5203 } else {
5204 try {
5205 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005206 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005207 } catch (RemoteException ex) {
5208 }
5209 }
5210 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005211 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005212 return;
5213 }
5214
5215 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005216 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217 // Right now, if you are not the original owner of the permission,
5218 // you are not allowed to revoke it.
5219 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5220 throw new SecurityException("Uid " + callingUid
5221 + " does not have permission to uri " + uri);
5222 //}
5223 }
5224
5225 // Go through all of the permissions and remove any that match.
5226 final List<String> SEGMENTS = uri.getPathSegments();
5227 if (SEGMENTS != null) {
5228 final int NS = SEGMENTS.size();
5229 int N = mGrantedUriPermissions.size();
5230 for (int i=0; i<N; i++) {
5231 HashMap<Uri, UriPermission> perms
5232 = mGrantedUriPermissions.valueAt(i);
5233 Iterator<UriPermission> it = perms.values().iterator();
5234 toploop:
5235 while (it.hasNext()) {
5236 UriPermission perm = it.next();
5237 Uri targetUri = perm.uri;
5238 if (!authority.equals(targetUri.getAuthority())) {
5239 continue;
5240 }
5241 List<String> targetSegments = targetUri.getPathSegments();
5242 if (targetSegments == null) {
5243 continue;
5244 }
5245 if (targetSegments.size() < NS) {
5246 continue;
5247 }
5248 for (int j=0; j<NS; j++) {
5249 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5250 continue toploop;
5251 }
5252 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005253 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005254 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005255 perm.clearModes(modeFlags);
5256 if (perm.modeFlags == 0) {
5257 it.remove();
5258 }
5259 }
5260 if (perms.size() == 0) {
5261 mGrantedUriPermissions.remove(
5262 mGrantedUriPermissions.keyAt(i));
5263 N--;
5264 i--;
5265 }
5266 }
5267 }
5268 }
5269
5270 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5271 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005272 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 synchronized(this) {
5274 final ProcessRecord r = getRecordForAppLocked(caller);
5275 if (r == null) {
5276 throw new SecurityException("Unable to find app for caller "
5277 + caller
5278 + " when revoking permission to uri " + uri);
5279 }
5280 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005281 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005282 return;
5283 }
5284
5285 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5286 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5287 if (modeFlags == 0) {
5288 return;
5289 }
5290
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005291 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005292
5293 final String authority = uri.getAuthority();
5294 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005295 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005296 if (cpr != null) {
5297 pi = cpr.info;
5298 } else {
5299 try {
5300 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005301 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005302 } catch (RemoteException ex) {
5303 }
5304 }
5305 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005306 Slog.w(TAG, "No content provider found for permission revoke: "
5307 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005308 return;
5309 }
5310
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005311 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 }
5313 }
5314
Dianne Hackborn7e269642010-08-25 19:50:20 -07005315 @Override
5316 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005317 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005318 synchronized(this) {
5319 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5320 return owner.getExternalTokenLocked();
5321 }
5322 }
5323
5324 @Override
5325 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5326 Uri uri, int modeFlags) {
5327 synchronized(this) {
5328 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5329 if (owner == null) {
5330 throw new IllegalArgumentException("Unknown owner: " + token);
5331 }
5332 if (fromUid != Binder.getCallingUid()) {
5333 if (Binder.getCallingUid() != Process.myUid()) {
5334 // Only system code can grant URI permissions on behalf
5335 // of other users.
5336 throw new SecurityException("nice try");
5337 }
5338 }
5339 if (targetPkg == null) {
5340 throw new IllegalArgumentException("null target");
5341 }
5342 if (uri == null) {
5343 throw new IllegalArgumentException("null uri");
5344 }
5345
5346 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5347 }
5348 }
5349
5350 @Override
5351 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5352 synchronized(this) {
5353 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5354 if (owner == null) {
5355 throw new IllegalArgumentException("Unknown owner: " + token);
5356 }
5357
5358 if (uri == null) {
5359 owner.removeUriPermissionsLocked(mode);
5360 } else {
5361 owner.removeUriPermissionLocked(uri, mode);
5362 }
5363 }
5364 }
5365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005366 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5367 synchronized (this) {
5368 ProcessRecord app =
5369 who != null ? getRecordForAppLocked(who) : null;
5370 if (app == null) return;
5371
5372 Message msg = Message.obtain();
5373 msg.what = WAIT_FOR_DEBUGGER_MSG;
5374 msg.obj = app;
5375 msg.arg1 = waiting ? 1 : 0;
5376 mHandler.sendMessage(msg);
5377 }
5378 }
5379
5380 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005381 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5382 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005383 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005384 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005385 outInfo.threshold = homeAppMem;
5386 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5387 outInfo.hiddenAppThreshold = hiddenAppMem;
5388 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005389 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005390 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5391 ProcessList.VISIBLE_APP_ADJ);
5392 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5393 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005394 }
5395
5396 // =========================================================
5397 // TASK MANAGEMENT
5398 // =========================================================
5399
5400 public List getTasks(int maxNum, int flags,
5401 IThumbnailReceiver receiver) {
5402 ArrayList list = new ArrayList();
5403
5404 PendingThumbnailsRecord pending = null;
5405 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005406 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005407
5408 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005409 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005410 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5411 + ", receiver=" + receiver);
5412
5413 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5414 != PackageManager.PERMISSION_GRANTED) {
5415 if (receiver != null) {
5416 // If the caller wants to wait for pending thumbnails,
5417 // it ain't gonna get them.
5418 try {
5419 receiver.finished();
5420 } catch (RemoteException ex) {
5421 }
5422 }
5423 String msg = "Permission Denial: getTasks() from pid="
5424 + Binder.getCallingPid()
5425 + ", uid=" + Binder.getCallingUid()
5426 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005427 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005428 throw new SecurityException(msg);
5429 }
5430
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005431 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005432 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005433 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005434 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 TaskRecord curTask = null;
5436 int numActivities = 0;
5437 int numRunning = 0;
5438 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005439 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005440 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005441 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005442
5443 // Initialize state for next task if needed.
5444 if (top == null ||
5445 (top.state == ActivityState.INITIALIZING
5446 && top.task == r.task)) {
5447 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 curTask = r.task;
5449 numActivities = numRunning = 0;
5450 }
5451
5452 // Add 'r' into the current task.
5453 numActivities++;
5454 if (r.app != null && r.app.thread != null) {
5455 numRunning++;
5456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457
Joe Onorato8a9b2202010-02-26 18:56:32 -08005458 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459 TAG, r.intent.getComponent().flattenToShortString()
5460 + ": task=" + r.task);
5461
5462 // If the next one is a different task, generate a new
5463 // TaskInfo entry for what we have.
5464 if (next == null || next.task != curTask) {
5465 ActivityManager.RunningTaskInfo ci
5466 = new ActivityManager.RunningTaskInfo();
5467 ci.id = curTask.taskId;
5468 ci.baseActivity = r.intent.getComponent();
5469 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005470 if (top.thumbHolder != null) {
5471 ci.description = top.thumbHolder.lastDescription;
5472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005473 ci.numActivities = numActivities;
5474 ci.numRunning = numRunning;
5475 //System.out.println(
5476 // "#" + maxNum + ": " + " descr=" + ci.description);
5477 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005478 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 TAG, "State=" + top.state + "Idle=" + top.idle
5480 + " app=" + top.app
5481 + " thr=" + (top.app != null ? top.app.thread : null));
5482 if (top.state == ActivityState.RESUMED
5483 || top.state == ActivityState.PAUSING) {
5484 if (top.idle && top.app != null
5485 && top.app.thread != null) {
5486 topRecord = top;
5487 topThumbnail = top.app.thread;
5488 } else {
5489 top.thumbnailNeeded = true;
5490 }
5491 }
5492 if (pending == null) {
5493 pending = new PendingThumbnailsRecord(receiver);
5494 }
5495 pending.pendingRecords.add(top);
5496 }
5497 list.add(ci);
5498 maxNum--;
5499 top = null;
5500 }
5501 }
5502
5503 if (pending != null) {
5504 mPendingThumbnails.add(pending);
5505 }
5506 }
5507
Joe Onorato8a9b2202010-02-26 18:56:32 -08005508 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509
5510 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005511 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005513 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005515 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005516 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 }
5518 }
5519
5520 if (pending == null && receiver != null) {
5521 // In this case all thumbnails were available and the client
5522 // is being asked to be told when the remaining ones come in...
5523 // which is unusually, since the top-most currently running
5524 // activity should never have a canned thumbnail! Oh well.
5525 try {
5526 receiver.finished();
5527 } catch (RemoteException ex) {
5528 }
5529 }
5530
5531 return list;
5532 }
5533
5534 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5535 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005536 final int callingUid = Binder.getCallingUid();
5537 // If it's the system uid asking, then use the current user id.
5538 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5539 // require the entire list.
5540 final int callingUserId = callingUid == Process.SYSTEM_UID
5541 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 synchronized (this) {
5543 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5544 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005545 final boolean detailed = checkCallingPermission(
5546 android.Manifest.permission.GET_DETAILED_TASKS)
5547 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005549 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551 final int N = mRecentTasks.size();
5552 ArrayList<ActivityManager.RecentTaskInfo> res
5553 = new ArrayList<ActivityManager.RecentTaskInfo>(
5554 maxNum < N ? maxNum : N);
5555 for (int i=0; i<N && maxNum > 0; i++) {
5556 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005557 // Only add calling user's recent tasks
5558 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005559 // Return the entry if desired by the caller. We always return
5560 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005561 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005562 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5563 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005564
Dianne Hackborn905577f2011-09-07 18:31:28 -07005565 if (i == 0
5566 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 || (tr.intent == null)
5568 || ((tr.intent.getFlags()
5569 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5570 ActivityManager.RecentTaskInfo rti
5571 = new ActivityManager.RecentTaskInfo();
5572 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005573 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 rti.baseIntent = new Intent(
5575 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005576 if (!detailed) {
5577 rti.baseIntent.replaceExtras((Bundle)null);
5578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005580 rti.description = tr.lastDescription;
5581
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005582 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5583 // Check whether this activity is currently available.
5584 try {
5585 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005586 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5587 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005588 continue;
5589 }
5590 } else if (rti.baseIntent != null) {
5591 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005592 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005593 continue;
5594 }
5595 }
5596 } catch (RemoteException e) {
5597 // Will never happen.
5598 }
5599 }
5600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 res.add(rti);
5602 maxNum--;
5603 }
5604 }
5605 return res;
5606 }
5607 }
5608
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005609 private TaskRecord taskForIdLocked(int id) {
5610 final int N = mRecentTasks.size();
5611 for (int i=0; i<N; i++) {
5612 TaskRecord tr = mRecentTasks.get(i);
5613 if (tr.taskId == id) {
5614 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005615 }
5616 }
5617 return null;
5618 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005619
5620 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5621 synchronized (this) {
5622 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5623 "getTaskThumbnails()");
5624 TaskRecord tr = taskForIdLocked(id);
5625 if (tr != null) {
5626 return mMainStack.getTaskThumbnailsLocked(tr);
5627 }
5628 }
5629 return null;
5630 }
5631
5632 public boolean removeSubTask(int taskId, int subTaskIndex) {
5633 synchronized (this) {
5634 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5635 "removeSubTask()");
5636 long ident = Binder.clearCallingIdentity();
5637 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005638 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5639 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005640 } finally {
5641 Binder.restoreCallingIdentity(ident);
5642 }
5643 }
5644 }
5645
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005646 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5647 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005648 Intent baseIntent = new Intent(
5649 tr.intent != null ? tr.intent : tr.affinityIntent);
5650 ComponentName component = baseIntent.getComponent();
5651 if (component == null) {
5652 Slog.w(TAG, "Now component for base intent of task: " + tr);
5653 return;
5654 }
5655
5656 // Find any running services associated with this app.
5657 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005658 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005659 if (sr.packageName.equals(component.getPackageName())) {
5660 services.add(sr);
5661 }
5662 }
5663
5664 // Take care of any running services associated with the app.
5665 for (int i=0; i<services.size(); i++) {
5666 ServiceRecord sr = services.get(i);
5667 if (sr.startRequested) {
5668 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005669 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005670 stopServiceLocked(sr);
5671 } else {
5672 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005673 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005674 if (sr.app != null && sr.app.thread != null) {
5675 sendServiceArgsLocked(sr, false);
5676 }
5677 }
5678 }
5679 }
5680
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005681 if (killProcesses) {
5682 // Find any running processes associated with this app.
5683 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5684 SparseArray<ProcessRecord> appProcs
5685 = mProcessNames.getMap().get(component.getPackageName());
5686 if (appProcs != null) {
5687 for (int i=0; i<appProcs.size(); i++) {
5688 procs.add(appProcs.valueAt(i));
5689 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005690 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005691
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005692 // Kill the running processes.
5693 for (int i=0; i<procs.size(); i++) {
5694 ProcessRecord pr = procs.get(i);
5695 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5696 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5697 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5698 pr.processName, pr.setAdj, "remove task");
5699 Process.killProcessQuiet(pr.pid);
5700 } else {
5701 pr.waitingToKill = "remove task";
5702 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005703 }
5704 }
5705 }
5706
5707 public boolean removeTask(int taskId, int flags) {
5708 synchronized (this) {
5709 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5710 "removeTask()");
5711 long ident = Binder.clearCallingIdentity();
5712 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005713 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5714 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005715 if (r != null) {
5716 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005717 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005718 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005719 } else {
5720 TaskRecord tr = null;
5721 int i=0;
5722 while (i < mRecentTasks.size()) {
5723 TaskRecord t = mRecentTasks.get(i);
5724 if (t.taskId == taskId) {
5725 tr = t;
5726 break;
5727 }
5728 i++;
5729 }
5730 if (tr != null) {
5731 if (tr.numActivities <= 0) {
5732 // Caller is just removing a recent task that is
5733 // not actively running. That is easy!
5734 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005735 cleanUpRemovedTaskLocked(tr, flags);
5736 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005737 } else {
5738 Slog.w(TAG, "removeTask: task " + taskId
5739 + " does not have activities to remove, "
5740 + " but numActivities=" + tr.numActivities
5741 + ": " + tr);
5742 }
5743 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005744 }
5745 } finally {
5746 Binder.restoreCallingIdentity(ident);
5747 }
5748 }
5749 return false;
5750 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5753 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005754 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 TaskRecord jt = startTask;
5756
5757 // First look backwards
5758 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005759 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 if (r.task != jt) {
5761 jt = r.task;
5762 if (affinity.equals(jt.affinity)) {
5763 return j;
5764 }
5765 }
5766 }
5767
5768 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005769 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 jt = startTask;
5771 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005772 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773 if (r.task != jt) {
5774 if (affinity.equals(jt.affinity)) {
5775 return j;
5776 }
5777 jt = r.task;
5778 }
5779 }
5780
5781 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005782 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 return N-1;
5784 }
5785
5786 return -1;
5787 }
5788
5789 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005790 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005791 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005792 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005793 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5794 "moveTaskToFront()");
5795
5796 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005797 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5798 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005799 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005800 return;
5801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802 final long origId = Binder.clearCallingIdentity();
5803 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005804 TaskRecord tr = taskForIdLocked(task);
5805 if (tr != null) {
5806 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5807 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005809 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5810 // Caller wants the home activity moved with it. To accomplish this,
5811 // we'll just move the home task to the top first.
5812 mMainStack.moveHomeToFrontLocked();
5813 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005814 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005815 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005817 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5818 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005820 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5821 mMainStack.mUserLeaving = true;
5822 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005823 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5824 // Caller wants the home activity moved with it. To accomplish this,
5825 // we'll just move the home task to the top first.
5826 mMainStack.moveHomeToFrontLocked();
5827 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005828 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 return;
5830 }
5831 }
5832 } finally {
5833 Binder.restoreCallingIdentity(origId);
5834 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005835 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 }
5837 }
5838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 public void moveTaskToBack(int task) {
5840 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5841 "moveTaskToBack()");
5842
5843 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005844 if (mMainStack.mResumedActivity != null
5845 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005846 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5847 Binder.getCallingUid(), "Task to back")) {
5848 return;
5849 }
5850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005852 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 Binder.restoreCallingIdentity(origId);
5854 }
5855 }
5856
5857 /**
5858 * Moves an activity, and all of the other activities within the same task, to the bottom
5859 * of the history stack. The activity's order within the task is unchanged.
5860 *
5861 * @param token A reference to the activity we wish to move
5862 * @param nonRoot If false then this only works if the activity is the root
5863 * of a task; if true it will work for any activity in a task.
5864 * @return Returns true if the move completed, false if not.
5865 */
5866 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005867 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 synchronized(this) {
5869 final long origId = Binder.clearCallingIdentity();
5870 int taskId = getTaskForActivityLocked(token, !nonRoot);
5871 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005872 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 }
5874 Binder.restoreCallingIdentity(origId);
5875 }
5876 return false;
5877 }
5878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005879 public void moveTaskBackwards(int task) {
5880 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5881 "moveTaskBackwards()");
5882
5883 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005884 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5885 Binder.getCallingUid(), "Task backwards")) {
5886 return;
5887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 final long origId = Binder.clearCallingIdentity();
5889 moveTaskBackwardsLocked(task);
5890 Binder.restoreCallingIdentity(origId);
5891 }
5892 }
5893
5894 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005895 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005896 }
5897
5898 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5899 synchronized(this) {
5900 return getTaskForActivityLocked(token, onlyRoot);
5901 }
5902 }
5903
5904 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005905 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005906 TaskRecord lastTask = null;
5907 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005908 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005909 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005910 if (!onlyRoot || lastTask != r.task) {
5911 return r.task.taskId;
5912 }
5913 return -1;
5914 }
5915 lastTask = r.task;
5916 }
5917
5918 return -1;
5919 }
5920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 // =========================================================
5922 // THUMBNAILS
5923 // =========================================================
5924
5925 public void reportThumbnail(IBinder token,
5926 Bitmap thumbnail, CharSequence description) {
5927 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5928 final long origId = Binder.clearCallingIdentity();
5929 sendPendingThumbnail(null, token, thumbnail, description, true);
5930 Binder.restoreCallingIdentity(origId);
5931 }
5932
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005933 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 Bitmap thumbnail, CharSequence description, boolean always) {
5935 TaskRecord task = null;
5936 ArrayList receivers = null;
5937
5938 //System.out.println("Send pending thumbnail: " + r);
5939
5940 synchronized(this) {
5941 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005942 r = mMainStack.isInStackLocked(token);
5943 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005944 return;
5945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005947 if (thumbnail == null && r.thumbHolder != null) {
5948 thumbnail = r.thumbHolder.lastThumbnail;
5949 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005950 }
5951 if (thumbnail == null && !always) {
5952 // If there is no thumbnail, and this entry is not actually
5953 // going away, then abort for now and pick up the next
5954 // thumbnail we get.
5955 return;
5956 }
5957 task = r.task;
5958
5959 int N = mPendingThumbnails.size();
5960 int i=0;
5961 while (i<N) {
5962 PendingThumbnailsRecord pr =
5963 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5964 //System.out.println("Looking in " + pr.pendingRecords);
5965 if (pr.pendingRecords.remove(r)) {
5966 if (receivers == null) {
5967 receivers = new ArrayList();
5968 }
5969 receivers.add(pr);
5970 if (pr.pendingRecords.size() == 0) {
5971 pr.finished = true;
5972 mPendingThumbnails.remove(i);
5973 N--;
5974 continue;
5975 }
5976 }
5977 i++;
5978 }
5979 }
5980
5981 if (receivers != null) {
5982 final int N = receivers.size();
5983 for (int i=0; i<N; i++) {
5984 try {
5985 PendingThumbnailsRecord pr =
5986 (PendingThumbnailsRecord)receivers.get(i);
5987 pr.receiver.newThumbnail(
5988 task != null ? task.taskId : -1, thumbnail, description);
5989 if (pr.finished) {
5990 pr.receiver.finished();
5991 }
5992 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005993 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 }
5995 }
5996 }
5997 }
5998
5999 // =========================================================
6000 // CONTENT PROVIDERS
6001 // =========================================================
6002
Jeff Brown10e89712011-07-08 18:52:57 -07006003 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6004 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006005 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006006 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006007 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006008 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 } catch (RemoteException ex) {
6010 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006011 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006012 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6013 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006014 if (providers != null) {
6015 final int N = providers.size();
6016 for (int i=0; i<N; i++) {
6017 ProviderInfo cpi =
6018 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07006019
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006020 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006021 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006023 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07006024 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006026 if (DEBUG_MU)
6027 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 app.pubProviders.put(cpi.name, cpr);
6029 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006030 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 }
6032 }
6033 return providers;
6034 }
6035
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006036 /**
6037 * Check if {@link ProcessRecord} has a possible chance at accessing the
6038 * given {@link ProviderInfo}. Final permission checking is always done
6039 * in {@link ContentProvider}.
6040 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006042 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006044 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006046 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006047 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 return null;
6049 }
6050 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006051 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 == PackageManager.PERMISSION_GRANTED) {
6053 return null;
6054 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006055
6056 PathPermission[] pps = cpi.pathPermissions;
6057 if (pps != null) {
6058 int i = pps.length;
6059 while (i > 0) {
6060 i--;
6061 PathPermission pp = pps[i];
6062 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006063 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006064 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006065 return null;
6066 }
6067 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006068 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006069 == PackageManager.PERMISSION_GRANTED) {
6070 return null;
6071 }
6072 }
6073 }
6074
Dianne Hackbornb424b632010-08-18 15:59:05 -07006075 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6076 if (perms != null) {
6077 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6078 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6079 return null;
6080 }
6081 }
6082 }
6083
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006084 String msg;
6085 if (!cpi.exported) {
6086 msg = "Permission Denial: opening provider " + cpi.name
6087 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6088 + ", uid=" + callingUid + ") that is not exported from uid "
6089 + cpi.applicationInfo.uid;
6090 } else {
6091 msg = "Permission Denial: opening provider " + cpi.name
6092 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6093 + ", uid=" + callingUid + ") requires "
6094 + cpi.readPermission + " or " + cpi.writePermission;
6095 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006096 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 return msg;
6098 }
6099
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006100 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6101 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006102 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006103 for (int i=0; i<r.conProviders.size(); i++) {
6104 ContentProviderConnection conn = r.conProviders.get(i);
6105 if (conn.provider == cpr) {
6106 if (DEBUG_PROVIDER) Slog.v(TAG,
6107 "Adding provider requested by "
6108 + r.processName + " from process "
6109 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6110 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6111 if (stable) {
6112 conn.stableCount++;
6113 conn.numStableIncs++;
6114 } else {
6115 conn.unstableCount++;
6116 conn.numUnstableIncs++;
6117 }
6118 return conn;
6119 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006120 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006121 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6122 if (stable) {
6123 conn.stableCount = 1;
6124 conn.numStableIncs = 1;
6125 } else {
6126 conn.unstableCount = 1;
6127 conn.numUnstableIncs = 1;
6128 }
6129 cpr.connections.add(conn);
6130 r.conProviders.add(conn);
6131 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006132 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006133 cpr.addExternalProcessHandleLocked(externalProcessToken);
6134 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006135 }
6136
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006137 boolean decProviderCountLocked(ContentProviderConnection conn,
6138 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6139 if (conn != null) {
6140 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006141 if (DEBUG_PROVIDER) Slog.v(TAG,
6142 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006143 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006144 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006145 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6146 if (stable) {
6147 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006148 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006149 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006150 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006151 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6152 cpr.connections.remove(conn);
6153 conn.client.conProviders.remove(conn);
6154 return true;
6155 }
6156 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006157 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006158 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006159 return false;
6160 }
6161
Amith Yamasani742a6712011-05-04 14:49:28 -07006162 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006163 String name, IBinder token, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006165 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 ProviderInfo cpi = null;
6167
6168 synchronized(this) {
6169 ProcessRecord r = null;
6170 if (caller != null) {
6171 r = getRecordForAppLocked(caller);
6172 if (r == null) {
6173 throw new SecurityException(
6174 "Unable to find app for caller " + caller
6175 + " (pid=" + Binder.getCallingPid()
6176 + ") when getting content provider " + name);
6177 }
6178 }
6179
6180 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006181 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006182 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006183 boolean providerRunning = cpr != null;
6184 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006186 String msg;
6187 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6188 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 }
6190
6191 if (r != null && cpr.canRunHere(r)) {
6192 // This provider has been published or is in the process
6193 // of being published... but it is also allowed to run
6194 // in the caller's process, so don't make a connection
6195 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006196 ContentProviderHolder holder = cpr.newHolder(null);
6197 // don't give caller the provider object, it needs
6198 // to make its own.
6199 holder.provider = null;
6200 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 }
6202
6203 final long origId = Binder.clearCallingIdentity();
6204
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006205 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006207 conn = incProviderCountLocked(r, cpr, token, stable);
6208 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006209 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006210 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006211 // make sure to count it as being accessed and thus
6212 // back up on the LRU list. This is good because
6213 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006214 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006215 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006216 }
6217
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006218 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006219 if (false) {
6220 if (cpr.name.flattenToShortString().equals(
6221 "com.android.providers.calendar/.CalendarProvider2")) {
6222 Slog.v(TAG, "****************** KILLING "
6223 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006224 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006225 }
6226 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006227 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006228 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6229 // NOTE: there is still a race here where a signal could be
6230 // pending on the process even though we managed to update its
6231 // adj level. Not sure what to do about this, but at least
6232 // the race is now smaller.
6233 if (!success) {
6234 // Uh oh... it looks like the provider's process
6235 // has been killed on us. We need to wait for a new
6236 // process to be started, and make sure its death
6237 // doesn't kill our process.
6238 Slog.i(TAG,
6239 "Existing provider " + cpr.name.flattenToShortString()
6240 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006241 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006242 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006243 if (!lastRef) {
6244 // This wasn't the last ref our process had on
6245 // the provider... we have now been killed, bail.
6246 return null;
6247 }
6248 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006249 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 }
6252
6253 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006256 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006258 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006259 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006260 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 } catch (RemoteException ex) {
6262 }
6263 if (cpi == null) {
6264 return null;
6265 }
Amith Yamasania4a54e22012-04-16 15:44:19 -07006266 if (isSingleton(cpi.processName, cpi.applicationInfo)) {
6267 userId = 0;
6268 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006269 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006270
Dianne Hackbornb424b632010-08-18 15:59:05 -07006271 String msg;
6272 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6273 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 }
6275
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006276 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006277 && !cpi.processName.equals("system")) {
6278 // If this content provider does not run in the system
6279 // process, and the system is not yet ready to run other
6280 // processes, then fail fast instead of hanging.
6281 throw new IllegalArgumentException(
6282 "Attempt to launch content provider before system ready");
6283 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006284
6285 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006286 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006287 final boolean firstClass = cpr == null;
6288 if (firstClass) {
6289 try {
6290 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006291 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 getApplicationInfo(
6293 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006294 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006296 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 + cpi.name);
6298 return null;
6299 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006300 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006301 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 } catch (RemoteException ex) {
6303 // pm is in same process, this will never happen.
6304 }
6305 }
6306
6307 if (r != null && cpr.canRunHere(r)) {
6308 // If this is a multiprocess provider, then just return its
6309 // info and allow the caller to instantiate it. Only do
6310 // this if the provider is the same user as the caller's
6311 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006312 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 }
6314
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006315 if (DEBUG_PROVIDER) {
6316 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006317 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006318 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 }
6320
6321 // This is single process, and our app is now connecting to it.
6322 // See if we are already in the process of launching this
6323 // provider.
6324 final int N = mLaunchingProviders.size();
6325 int i;
6326 for (i=0; i<N; i++) {
6327 if (mLaunchingProviders.get(i) == cpr) {
6328 break;
6329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330 }
6331
6332 // If the provider is not already being launched, then get it
6333 // started.
6334 if (i >= N) {
6335 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006336
6337 try {
6338 // Content provider is now in use, its package can't be stopped.
6339 try {
6340 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006341 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006342 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006343 } catch (IllegalArgumentException e) {
6344 Slog.w(TAG, "Failed trying to unstop package "
6345 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006346 }
6347
6348 ProcessRecord proc = startProcessLocked(cpi.processName,
6349 cpr.appInfo, false, 0, "content provider",
6350 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006351 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006352 if (proc == null) {
6353 Slog.w(TAG, "Unable to launch app "
6354 + cpi.applicationInfo.packageName + "/"
6355 + cpi.applicationInfo.uid + " for provider "
6356 + name + ": process is bad");
6357 return null;
6358 }
6359 cpr.launchingApp = proc;
6360 mLaunchingProviders.add(cpr);
6361 } finally {
6362 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006364 }
6365
6366 // Make sure the provider is published (the same provider class
6367 // may be published under multiple names).
6368 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006369 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006371
Amith Yamasani742a6712011-05-04 14:49:28 -07006372 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006373 conn = incProviderCountLocked(r, cpr, token, stable);
6374 if (conn != null) {
6375 conn.waiting = true;
6376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 }
6378 }
6379
6380 // Wait for the provider to be published...
6381 synchronized (cpr) {
6382 while (cpr.provider == null) {
6383 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006384 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 + cpi.applicationInfo.packageName + "/"
6386 + cpi.applicationInfo.uid + " for provider "
6387 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006388 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 cpi.applicationInfo.packageName,
6390 cpi.applicationInfo.uid, name);
6391 return null;
6392 }
6393 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006394 if (DEBUG_MU) {
6395 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6396 + cpr.launchingApp);
6397 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006398 if (conn != null) {
6399 conn.waiting = true;
6400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 cpr.wait();
6402 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006403 } finally {
6404 if (conn != null) {
6405 conn.waiting = false;
6406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 }
6408 }
6409 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006410 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 }
6412
6413 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006414 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006415 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 if (caller == null) {
6417 String msg = "null IApplicationThread when getting content provider "
6418 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006419 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 throw new SecurityException(msg);
6421 }
6422
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006423 return getContentProviderImpl(caller, name, null, stable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006424 }
6425
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006426 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6427 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6428 "Do not have permission in call getContentProviderExternal()");
6429 return getContentProviderExternalUnchecked(name, token);
6430 }
6431
6432 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006433 return getContentProviderImpl(null, name, token, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 }
6435
6436 /**
6437 * Drop a content provider from a ProcessRecord's bookkeeping
6438 * @param cpr
6439 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006440 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006441 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006443 ContentProviderConnection conn;
6444 try {
6445 conn = (ContentProviderConnection)connection;
6446 } catch (ClassCastException e) {
6447 String msg ="removeContentProvider: " + connection
6448 + " not a ContentProviderConnection";
6449 Slog.w(TAG, msg);
6450 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006452 if (conn == null) {
6453 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006455 if (decProviderCountLocked(conn, null, null, stable)) {
6456 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 }
6459 }
6460
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006461 public void removeContentProviderExternal(String name, IBinder token) {
6462 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6463 "Do not have permission in call removeContentProviderExternal()");
6464 removeContentProviderExternalUnchecked(name, token);
6465 }
6466
6467 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006469 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6470 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 if(cpr == null) {
6472 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006473 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 return;
6475 }
6476
6477 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006478 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006479 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6480 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006481 if (localCpr.hasExternalProcessHandles()) {
6482 if (localCpr.removeExternalProcessHandleLocked(token)) {
6483 updateOomAdjLocked();
6484 } else {
6485 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6486 + " with no external reference for token: "
6487 + token + ".");
6488 }
6489 } else {
6490 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6491 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 }
6494 }
6495
6496 public final void publishContentProviders(IApplicationThread caller,
6497 List<ContentProviderHolder> providers) {
6498 if (providers == null) {
6499 return;
6500 }
6501
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006502 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006503 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006504 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006505 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006506 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006507 if (r == null) {
6508 throw new SecurityException(
6509 "Unable to find app for caller " + caller
6510 + " (pid=" + Binder.getCallingPid()
6511 + ") when publishing content providers");
6512 }
6513
6514 final long origId = Binder.clearCallingIdentity();
6515
6516 final int N = providers.size();
6517 for (int i=0; i<N; i++) {
6518 ContentProviderHolder src = providers.get(i);
6519 if (src == null || src.info == null || src.provider == null) {
6520 continue;
6521 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006522 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006523 if (DEBUG_MU)
6524 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006526 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006527 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 String names[] = dst.info.authority.split(";");
6529 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006530 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 }
6532
6533 int NL = mLaunchingProviders.size();
6534 int j;
6535 for (j=0; j<NL; j++) {
6536 if (mLaunchingProviders.get(j) == dst) {
6537 mLaunchingProviders.remove(j);
6538 j--;
6539 NL--;
6540 }
6541 }
6542 synchronized (dst) {
6543 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006544 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006545 dst.notifyAll();
6546 }
6547 updateOomAdjLocked(r);
6548 }
6549 }
6550
6551 Binder.restoreCallingIdentity(origId);
6552 }
6553 }
6554
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006555 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6556 ContentProviderConnection conn;
6557 try {
6558 conn = (ContentProviderConnection)connection;
6559 } catch (ClassCastException e) {
6560 String msg ="refContentProvider: " + connection
6561 + " not a ContentProviderConnection";
6562 Slog.w(TAG, msg);
6563 throw new IllegalArgumentException(msg);
6564 }
6565 if (conn == null) {
6566 throw new NullPointerException("connection is null");
6567 }
6568
6569 synchronized (this) {
6570 if (stable > 0) {
6571 conn.numStableIncs += stable;
6572 }
6573 stable = conn.stableCount + stable;
6574 if (stable < 0) {
6575 throw new IllegalStateException("stableCount < 0: " + stable);
6576 }
6577
6578 if (unstable > 0) {
6579 conn.numUnstableIncs += unstable;
6580 }
6581 unstable = conn.unstableCount + unstable;
6582 if (unstable < 0) {
6583 throw new IllegalStateException("unstableCount < 0: " + unstable);
6584 }
6585
6586 if ((stable+unstable) <= 0) {
6587 throw new IllegalStateException("ref counts can't go to zero here: stable="
6588 + stable + " unstable=" + unstable);
6589 }
6590 conn.stableCount = stable;
6591 conn.unstableCount = unstable;
6592 return !conn.dead;
6593 }
6594 }
6595
6596 public void unstableProviderDied(IBinder connection) {
6597 ContentProviderConnection conn;
6598 try {
6599 conn = (ContentProviderConnection)connection;
6600 } catch (ClassCastException e) {
6601 String msg ="refContentProvider: " + connection
6602 + " not a ContentProviderConnection";
6603 Slog.w(TAG, msg);
6604 throw new IllegalArgumentException(msg);
6605 }
6606 if (conn == null) {
6607 throw new NullPointerException("connection is null");
6608 }
6609
6610 // Safely retrieve the content provider associated with the connection.
6611 IContentProvider provider;
6612 synchronized (this) {
6613 provider = conn.provider.provider;
6614 }
6615
6616 if (provider == null) {
6617 // Um, yeah, we're way ahead of you.
6618 return;
6619 }
6620
6621 // Make sure the caller is being honest with us.
6622 if (provider.asBinder().pingBinder()) {
6623 // Er, no, still looks good to us.
6624 synchronized (this) {
6625 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6626 + " says " + conn + " died, but we don't agree");
6627 return;
6628 }
6629 }
6630
6631 // Well look at that! It's dead!
6632 synchronized (this) {
6633 if (conn.provider.provider != provider) {
6634 // But something changed... good enough.
6635 return;
6636 }
6637
6638 ProcessRecord proc = conn.provider.proc;
6639 if (proc == null || proc.thread == null) {
6640 // Seems like the process is already cleaned up.
6641 return;
6642 }
6643
6644 // As far as we're concerned, this is just like receiving a
6645 // death notification... just a bit prematurely.
6646 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6647 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006648 final long ident = Binder.clearCallingIdentity();
6649 try {
6650 appDiedLocked(proc, proc.pid, proc.thread);
6651 } finally {
6652 Binder.restoreCallingIdentity(ident);
6653 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006654 }
6655 }
6656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006657 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006658 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006659 synchronized (mSelf) {
6660 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6661 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006662 if (providers != null) {
6663 for (int i=providers.size()-1; i>=0; i--) {
6664 ProviderInfo pi = (ProviderInfo)providers.get(i);
6665 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6666 Slog.w(TAG, "Not installing system proc provider " + pi.name
6667 + ": not system .apk");
6668 providers.remove(i);
6669 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006670 }
6671 }
6672 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006673 if (providers != null) {
6674 mSystemThread.installSystemProviders(providers);
6675 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006676
6677 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006678
6679 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006680 }
6681
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006682 /**
6683 * Allows app to retrieve the MIME type of a URI without having permission
6684 * to access its content provider.
6685 *
6686 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6687 *
6688 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6689 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6690 */
6691 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006692 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006693 final String name = uri.getAuthority();
6694 final long ident = Binder.clearCallingIdentity();
6695 ContentProviderHolder holder = null;
6696
6697 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006698 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006699 if (holder != null) {
6700 return holder.provider.getType(uri);
6701 }
6702 } catch (RemoteException e) {
6703 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6704 return null;
6705 } finally {
6706 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006707 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006708 }
6709 Binder.restoreCallingIdentity(ident);
6710 }
6711
6712 return null;
6713 }
6714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 // =========================================================
6716 // GLOBAL MANAGEMENT
6717 // =========================================================
6718
6719 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006720 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006721 String proc = customProcess != null ? customProcess : info.processName;
6722 BatteryStatsImpl.Uid.Proc ps = null;
6723 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006724 int uid = info.uid;
6725 if (isolated) {
6726 int userId = UserId.getUserId(uid);
6727 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6728 uid = 0;
6729 while (true) {
6730 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6731 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6732 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6733 }
6734 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6735 mNextIsolatedProcessUid++;
6736 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6737 // No process for this uid, use it.
6738 break;
6739 }
6740 stepsLeft--;
6741 if (stepsLeft <= 0) {
6742 return null;
6743 }
6744 }
6745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006746 synchronized (stats) {
6747 ps = stats.getProcessStatsLocked(info.uid, proc);
6748 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006749 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 }
6751
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006752 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6753 ProcessRecord app;
6754 if (!isolated) {
6755 app = getProcessRecordLocked(info.processName, info.uid);
6756 } else {
6757 app = null;
6758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759
6760 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006761 app = newProcessRecordLocked(null, info, null, isolated);
6762 mProcessNames.put(info.processName, app.uid, app);
6763 if (isolated) {
6764 mIsolatedProcesses.put(app.uid, app);
6765 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006766 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 }
6768
Dianne Hackborne7f97212011-02-24 14:40:20 -08006769 // This package really, really can not be stopped.
6770 try {
6771 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006772 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006773 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006774 } catch (IllegalArgumentException e) {
6775 Slog.w(TAG, "Failed trying to unstop package "
6776 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006777 }
6778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006779 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6780 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6781 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006782 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 }
6784 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6785 mPersistentStartingProcesses.add(app);
6786 startProcessLocked(app, "added application", app.processName);
6787 }
6788
6789 return app;
6790 }
6791
6792 public void unhandledBack() {
6793 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6794 "unhandledBack()");
6795
6796 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006797 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006798 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 TAG, "Performing unhandledBack(): stack size = " + count);
6800 if (count > 1) {
6801 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006802 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006803 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6804 Binder.restoreCallingIdentity(origId);
6805 }
6806 }
6807 }
6808
6809 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006810 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006811 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006812 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 ParcelFileDescriptor pfd = null;
6814 if (cph != null) {
6815 // We record the binder invoker's uid in thread-local storage before
6816 // going to the content provider to open the file. Later, in the code
6817 // that handles all permissions checks, we look for this uid and use
6818 // that rather than the Activity Manager's own uid. The effect is that
6819 // we do the check against the caller's permissions even though it looks
6820 // to the content provider like the Activity Manager itself is making
6821 // the request.
6822 sCallerIdentity.set(new Identity(
6823 Binder.getCallingPid(), Binder.getCallingUid()));
6824 try {
6825 pfd = cph.provider.openFile(uri, "r");
6826 } catch (FileNotFoundException e) {
6827 // do nothing; pfd will be returned null
6828 } finally {
6829 // Ensure that whatever happens, we clean up the identity state
6830 sCallerIdentity.remove();
6831 }
6832
6833 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006834 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006835 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006836 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837 }
6838 return pfd;
6839 }
6840
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006841 // Actually is sleeping or shutting down or whatever else in the future
6842 // is an inactive state.
6843 public boolean isSleeping() {
6844 return mSleeping || mShuttingDown;
6845 }
6846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006847 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006848 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6849 != PackageManager.PERMISSION_GRANTED) {
6850 throw new SecurityException("Requires permission "
6851 + android.Manifest.permission.DEVICE_POWER);
6852 }
6853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006854 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006855 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006856 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006858 if (!mSleeping) {
6859 mSleeping = true;
6860 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006861
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006862 // Initialize the wake times of all processes.
6863 checkExcessivePowerUsageLocked(false);
6864 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6865 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6866 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6867 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006868 }
6869 }
6870
Dianne Hackborn55280a92009-05-07 15:53:46 -07006871 public boolean shutdown(int timeout) {
6872 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6873 != PackageManager.PERMISSION_GRANTED) {
6874 throw new SecurityException("Requires permission "
6875 + android.Manifest.permission.SHUTDOWN);
6876 }
6877
6878 boolean timedout = false;
6879
6880 synchronized(this) {
6881 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006882 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006883
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006884 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006885 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006886 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006887 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006888 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006889 long delay = endTime - System.currentTimeMillis();
6890 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006891 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006892 timedout = true;
6893 break;
6894 }
6895 try {
6896 this.wait();
6897 } catch (InterruptedException e) {
6898 }
6899 }
6900 }
6901 }
6902
6903 mUsageStatsService.shutdown();
6904 mBatteryStatsService.shutdown();
6905
6906 return timedout;
6907 }
6908
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006909 public final void activitySlept(IBinder token) {
6910 if (localLOGV) Slog.v(
6911 TAG, "Activity slept: token=" + token);
6912
6913 ActivityRecord r = null;
6914
6915 final long origId = Binder.clearCallingIdentity();
6916
6917 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006918 r = mMainStack.isInStackLocked(token);
6919 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006920 mMainStack.activitySleptLocked(r);
6921 }
6922 }
6923
6924 Binder.restoreCallingIdentity(origId);
6925 }
6926
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006927 private void comeOutOfSleepIfNeededLocked() {
6928 if (!mWentToSleep && !mLockScreenShown) {
6929 if (mSleeping) {
6930 mSleeping = false;
6931 mMainStack.awakeFromSleepingLocked();
6932 mMainStack.resumeTopActivityLocked(null);
6933 }
6934 }
6935 }
6936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006937 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006938 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6939 != PackageManager.PERMISSION_GRANTED) {
6940 throw new SecurityException("Requires permission "
6941 + android.Manifest.permission.DEVICE_POWER);
6942 }
6943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006944 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006945 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07006946 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006947 comeOutOfSleepIfNeededLocked();
6948 }
6949 }
6950
Jeff Brownc042ee22012-05-08 13:03:42 -07006951 private void updateEventDispatchingLocked() {
6952 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
6953 }
6954
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006955 public void setLockScreenShown(boolean shown) {
6956 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6957 != PackageManager.PERMISSION_GRANTED) {
6958 throw new SecurityException("Requires permission "
6959 + android.Manifest.permission.DEVICE_POWER);
6960 }
6961
6962 synchronized(this) {
6963 mLockScreenShown = shown;
6964 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006965 }
6966 }
6967
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006968 public void stopAppSwitches() {
6969 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6970 != PackageManager.PERMISSION_GRANTED) {
6971 throw new SecurityException("Requires permission "
6972 + android.Manifest.permission.STOP_APP_SWITCHES);
6973 }
6974
6975 synchronized(this) {
6976 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6977 + APP_SWITCH_DELAY_TIME;
6978 mDidAppSwitch = false;
6979 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6980 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6981 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6982 }
6983 }
6984
6985 public void resumeAppSwitches() {
6986 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6987 != PackageManager.PERMISSION_GRANTED) {
6988 throw new SecurityException("Requires permission "
6989 + android.Manifest.permission.STOP_APP_SWITCHES);
6990 }
6991
6992 synchronized(this) {
6993 // Note that we don't execute any pending app switches... we will
6994 // let those wait until either the timeout, or the next start
6995 // activity request.
6996 mAppSwitchesAllowedTime = 0;
6997 }
6998 }
6999
7000 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7001 String name) {
7002 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7003 return true;
7004 }
7005
7006 final int perm = checkComponentPermission(
7007 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007008 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007009 if (perm == PackageManager.PERMISSION_GRANTED) {
7010 return true;
7011 }
7012
Joe Onorato8a9b2202010-02-26 18:56:32 -08007013 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007014 return false;
7015 }
7016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017 public void setDebugApp(String packageName, boolean waitForDebugger,
7018 boolean persistent) {
7019 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7020 "setDebugApp()");
7021
7022 // Note that this is not really thread safe if there are multiple
7023 // callers into it at the same time, but that's not a situation we
7024 // care about.
7025 if (persistent) {
7026 final ContentResolver resolver = mContext.getContentResolver();
7027 Settings.System.putString(
7028 resolver, Settings.System.DEBUG_APP,
7029 packageName);
7030 Settings.System.putInt(
7031 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7032 waitForDebugger ? 1 : 0);
7033 }
7034
7035 synchronized (this) {
7036 if (!persistent) {
7037 mOrigDebugApp = mDebugApp;
7038 mOrigWaitForDebugger = mWaitForDebugger;
7039 }
7040 mDebugApp = packageName;
7041 mWaitForDebugger = waitForDebugger;
7042 mDebugTransient = !persistent;
7043 if (packageName != null) {
7044 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07007045 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007046 Binder.restoreCallingIdentity(origId);
7047 }
7048 }
7049 }
7050
Siva Velusamy92a8b222012-03-09 16:24:04 -08007051 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7052 synchronized (this) {
7053 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7054 if (!isDebuggable) {
7055 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7056 throw new SecurityException("Process not debuggable: " + app.packageName);
7057 }
7058 }
7059
7060 mOpenGlTraceApp = processName;
7061 }
7062 }
7063
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007064 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7065 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7066 synchronized (this) {
7067 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7068 if (!isDebuggable) {
7069 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7070 throw new SecurityException("Process not debuggable: " + app.packageName);
7071 }
7072 }
7073 mProfileApp = processName;
7074 mProfileFile = profileFile;
7075 if (mProfileFd != null) {
7076 try {
7077 mProfileFd.close();
7078 } catch (IOException e) {
7079 }
7080 mProfileFd = null;
7081 }
7082 mProfileFd = profileFd;
7083 mProfileType = 0;
7084 mAutoStopProfiler = autoStopProfiler;
7085 }
7086 }
7087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007088 public void setAlwaysFinish(boolean enabled) {
7089 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7090 "setAlwaysFinish()");
7091
7092 Settings.System.putInt(
7093 mContext.getContentResolver(),
7094 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7095
7096 synchronized (this) {
7097 mAlwaysFinishActivities = enabled;
7098 }
7099 }
7100
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007101 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007102 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007103 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007104 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007105 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007106 }
7107 }
7108
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007109 public boolean isUserAMonkey() {
7110 // For now the fact that there is a controller implies
7111 // we have a monkey.
7112 synchronized (this) {
7113 return mController != null;
7114 }
7115 }
7116
Jeff Sharkeya4620792011-05-20 15:29:23 -07007117 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007118 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7119 "registerProcessObserver()");
7120 synchronized (this) {
7121 mProcessObservers.register(observer);
7122 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007123 }
7124
7125 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007126 synchronized (this) {
7127 mProcessObservers.unregister(observer);
7128 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007129 }
7130
Daniel Sandler69a48172010-06-23 16:29:36 -04007131 public void setImmersive(IBinder token, boolean immersive) {
7132 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007133 ActivityRecord r = mMainStack.isInStackLocked(token);
7134 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007135 throw new IllegalArgumentException();
7136 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007137 r.immersive = immersive;
7138 }
7139 }
7140
7141 public boolean isImmersive(IBinder token) {
7142 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007143 ActivityRecord r = mMainStack.isInStackLocked(token);
7144 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007145 throw new IllegalArgumentException();
7146 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007147 return r.immersive;
7148 }
7149 }
7150
7151 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007152 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007153 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007154 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007155 return (r != null) ? r.immersive : false;
7156 }
7157 }
7158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007159 public final void enterSafeMode() {
7160 synchronized(this) {
7161 // It only makes sense to do this before the system is ready
7162 // and started launching other packages.
7163 if (!mSystemReady) {
7164 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007165 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007166 } catch (RemoteException e) {
7167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007168 }
7169 }
7170 }
7171
Jeff Brownb09abc12011-01-13 21:08:27 -08007172 public final void showSafeModeOverlay() {
7173 View v = LayoutInflater.from(mContext).inflate(
7174 com.android.internal.R.layout.safe_mode, null);
7175 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7176 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7177 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7178 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7179 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7180 lp.format = v.getBackground().getOpacity();
7181 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7182 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7183 ((WindowManager)mContext.getSystemService(
7184 Context.WINDOW_SERVICE)).addView(v, lp);
7185 }
7186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 public void noteWakeupAlarm(IIntentSender sender) {
7188 if (!(sender instanceof PendingIntentRecord)) {
7189 return;
7190 }
7191 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7192 synchronized (stats) {
7193 if (mBatteryStatsService.isOnBattery()) {
7194 mBatteryStatsService.enforceCallingPermission();
7195 PendingIntentRecord rec = (PendingIntentRecord)sender;
7196 int MY_UID = Binder.getCallingUid();
7197 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7198 BatteryStatsImpl.Uid.Pkg pkg =
7199 stats.getPackageStatsLocked(uid, rec.key.packageName);
7200 pkg.incWakeupsLocked();
7201 }
7202 }
7203 }
7204
Dianne Hackborn64825172011-03-02 21:32:58 -08007205 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007206 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007207 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007208 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007209 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007210 // XXX Note: don't acquire main activity lock here, because the window
7211 // manager calls in with its locks held.
7212
7213 boolean killed = false;
7214 synchronized (mPidsSelfLocked) {
7215 int[] types = new int[pids.length];
7216 int worstType = 0;
7217 for (int i=0; i<pids.length; i++) {
7218 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7219 if (proc != null) {
7220 int type = proc.setAdj;
7221 types[i] = type;
7222 if (type > worstType) {
7223 worstType = type;
7224 }
7225 }
7226 }
7227
Dianne Hackborn64825172011-03-02 21:32:58 -08007228 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007229 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007230 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7231 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007232 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007233 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007234
7235 // If this is not a secure call, don't let it kill processes that
7236 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007237 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7238 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007239 }
7240
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007241 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007242 for (int i=0; i<pids.length; i++) {
7243 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7244 if (proc == null) {
7245 continue;
7246 }
7247 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007248 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007249 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007250 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7251 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007252 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007253 proc.killedBackground = true;
7254 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007255 }
7256 }
7257 }
7258 return killed;
7259 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007260
7261 @Override
7262 public boolean killProcessesBelowForeground(String reason) {
7263 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7264 throw new SecurityException("killProcessesBelowForeground() only available to system");
7265 }
7266
7267 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7268 }
7269
7270 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7271 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7272 throw new SecurityException("killProcessesBelowAdj() only available to system");
7273 }
7274
7275 boolean killed = false;
7276 synchronized (mPidsSelfLocked) {
7277 final int size = mPidsSelfLocked.size();
7278 for (int i = 0; i < size; i++) {
7279 final int pid = mPidsSelfLocked.keyAt(i);
7280 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7281 if (proc == null) continue;
7282
7283 final int adj = proc.setAdj;
7284 if (adj > belowAdj && !proc.killedBackground) {
7285 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7286 EventLog.writeEvent(
7287 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7288 killed = true;
7289 proc.killedBackground = true;
7290 Process.killProcessQuiet(pid);
7291 }
7292 }
7293 }
7294 return killed;
7295 }
7296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007297 public final void startRunning(String pkg, String cls, String action,
7298 String data) {
7299 synchronized(this) {
7300 if (mStartRunning) {
7301 return;
7302 }
7303 mStartRunning = true;
7304 mTopComponent = pkg != null && cls != null
7305 ? new ComponentName(pkg, cls) : null;
7306 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7307 mTopData = data;
7308 if (!mSystemReady) {
7309 return;
7310 }
7311 }
7312
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007313 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007314 }
7315
7316 private void retrieveSettings() {
7317 final ContentResolver resolver = mContext.getContentResolver();
7318 String debugApp = Settings.System.getString(
7319 resolver, Settings.System.DEBUG_APP);
7320 boolean waitForDebugger = Settings.System.getInt(
7321 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7322 boolean alwaysFinishActivities = Settings.System.getInt(
7323 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7324
7325 Configuration configuration = new Configuration();
7326 Settings.System.getConfiguration(resolver, configuration);
7327
7328 synchronized (this) {
7329 mDebugApp = mOrigDebugApp = debugApp;
7330 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7331 mAlwaysFinishActivities = alwaysFinishActivities;
7332 // This happens before any activities are started, so we can
7333 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007334 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007335 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007336 }
7337 }
7338
7339 public boolean testIsSystemReady() {
7340 // no need to synchronize(this) just to read & return the value
7341 return mSystemReady;
7342 }
7343
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007344 private static File getCalledPreBootReceiversFile() {
7345 File dataDir = Environment.getDataDirectory();
7346 File systemDir = new File(dataDir, "system");
7347 File fname = new File(systemDir, "called_pre_boots.dat");
7348 return fname;
7349 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007350
7351 static final int LAST_DONE_VERSION = 10000;
7352
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007353 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7354 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7355 File file = getCalledPreBootReceiversFile();
7356 FileInputStream fis = null;
7357 try {
7358 fis = new FileInputStream(file);
7359 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007360 int fvers = dis.readInt();
7361 if (fvers == LAST_DONE_VERSION) {
7362 String vers = dis.readUTF();
7363 String codename = dis.readUTF();
7364 String build = dis.readUTF();
7365 if (android.os.Build.VERSION.RELEASE.equals(vers)
7366 && android.os.Build.VERSION.CODENAME.equals(codename)
7367 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7368 int num = dis.readInt();
7369 while (num > 0) {
7370 num--;
7371 String pkg = dis.readUTF();
7372 String cls = dis.readUTF();
7373 lastDoneReceivers.add(new ComponentName(pkg, cls));
7374 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007375 }
7376 }
7377 } catch (FileNotFoundException e) {
7378 } catch (IOException e) {
7379 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7380 } finally {
7381 if (fis != null) {
7382 try {
7383 fis.close();
7384 } catch (IOException e) {
7385 }
7386 }
7387 }
7388 return lastDoneReceivers;
7389 }
7390
7391 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7392 File file = getCalledPreBootReceiversFile();
7393 FileOutputStream fos = null;
7394 DataOutputStream dos = null;
7395 try {
7396 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7397 fos = new FileOutputStream(file);
7398 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007399 dos.writeInt(LAST_DONE_VERSION);
7400 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007401 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007402 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007403 dos.writeInt(list.size());
7404 for (int i=0; i<list.size(); i++) {
7405 dos.writeUTF(list.get(i).getPackageName());
7406 dos.writeUTF(list.get(i).getClassName());
7407 }
7408 } catch (IOException e) {
7409 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7410 file.delete();
7411 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007412 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007413 if (dos != null) {
7414 try {
7415 dos.close();
7416 } catch (IOException e) {
7417 // TODO Auto-generated catch block
7418 e.printStackTrace();
7419 }
7420 }
7421 }
7422 }
7423
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007424 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007425 synchronized(this) {
7426 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007427 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007428 return;
7429 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007430
7431 // Check to see if there are any update receivers to run.
7432 if (!mDidUpdate) {
7433 if (mWaitingUpdate) {
7434 return;
7435 }
7436 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7437 List<ResolveInfo> ris = null;
7438 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007439 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007440 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007441 } catch (RemoteException e) {
7442 }
7443 if (ris != null) {
7444 for (int i=ris.size()-1; i>=0; i--) {
7445 if ((ris.get(i).activityInfo.applicationInfo.flags
7446 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7447 ris.remove(i);
7448 }
7449 }
7450 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007451
7452 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7453
7454 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007455 for (int i=0; i<ris.size(); i++) {
7456 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007457 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7458 if (lastDoneReceivers.contains(comp)) {
7459 ris.remove(i);
7460 i--;
7461 }
7462 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007463
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007464 for (int i=0; i<ris.size(); i++) {
7465 ActivityInfo ai = ris.get(i).activityInfo;
7466 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7467 doneReceivers.add(comp);
7468 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007469 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007470 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007471 finisher = new IIntentReceiver.Stub() {
7472 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007473 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007474 boolean sticky) {
7475 // The raw IIntentReceiver interface is called
7476 // with the AM lock held, so redispatch to
7477 // execute our code without the lock.
7478 mHandler.post(new Runnable() {
7479 public void run() {
7480 synchronized (ActivityManagerService.this) {
7481 mDidUpdate = true;
7482 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007483 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007484 showBootMessage(mContext.getText(
7485 R.string.android_upgrading_complete),
7486 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007487 systemReady(goingCallback);
7488 }
7489 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007490 }
7491 };
7492 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007493 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007494 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007495 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007496 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007497 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007498 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007499 mWaitingUpdate = true;
7500 }
7501 }
7502 }
7503 if (mWaitingUpdate) {
7504 return;
7505 }
7506 mDidUpdate = true;
7507 }
7508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007509 mSystemReady = true;
7510 if (!mStartRunning) {
7511 return;
7512 }
7513 }
7514
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007515 ArrayList<ProcessRecord> procsToKill = null;
7516 synchronized(mPidsSelfLocked) {
7517 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7518 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7519 if (!isAllowedWhileBooting(proc.info)){
7520 if (procsToKill == null) {
7521 procsToKill = new ArrayList<ProcessRecord>();
7522 }
7523 procsToKill.add(proc);
7524 }
7525 }
7526 }
7527
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007528 synchronized(this) {
7529 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007530 for (int i=procsToKill.size()-1; i>=0; i--) {
7531 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007532 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007533 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007534 }
7535 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007536
7537 // Now that we have cleaned up any update processes, we
7538 // are ready to start launching real processes and know that
7539 // we won't trample on them any more.
7540 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007541 }
7542
Joe Onorato8a9b2202010-02-26 18:56:32 -08007543 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007544 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007545 SystemClock.uptimeMillis());
7546
7547 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007548 // Make sure we have no pre-ready processes sitting around.
7549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007550 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7551 ResolveInfo ri = mContext.getPackageManager()
7552 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007553 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554 CharSequence errorMsg = null;
7555 if (ri != null) {
7556 ActivityInfo ai = ri.activityInfo;
7557 ApplicationInfo app = ai.applicationInfo;
7558 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7559 mTopAction = Intent.ACTION_FACTORY_TEST;
7560 mTopData = null;
7561 mTopComponent = new ComponentName(app.packageName,
7562 ai.name);
7563 } else {
7564 errorMsg = mContext.getResources().getText(
7565 com.android.internal.R.string.factorytest_not_system);
7566 }
7567 } else {
7568 errorMsg = mContext.getResources().getText(
7569 com.android.internal.R.string.factorytest_no_action);
7570 }
7571 if (errorMsg != null) {
7572 mTopAction = null;
7573 mTopData = null;
7574 mTopComponent = null;
7575 Message msg = Message.obtain();
7576 msg.what = SHOW_FACTORY_ERROR_MSG;
7577 msg.getData().putCharSequence("msg", errorMsg);
7578 mHandler.sendMessage(msg);
7579 }
7580 }
7581 }
7582
7583 retrieveSettings();
7584
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007585 if (goingCallback != null) goingCallback.run();
7586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 synchronized (this) {
7588 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7589 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007590 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007591 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592 if (apps != null) {
7593 int N = apps.size();
7594 int i;
7595 for (i=0; i<N; i++) {
7596 ApplicationInfo info
7597 = (ApplicationInfo)apps.get(i);
7598 if (info != null &&
7599 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007600 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007601 }
7602 }
7603 }
7604 } catch (RemoteException ex) {
7605 // pm is in same process, this will never happen.
7606 }
7607 }
7608
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007609 // Start up initial activity.
7610 mBooting = true;
7611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007612 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007613 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007614 Message msg = Message.obtain();
7615 msg.what = SHOW_UID_ERROR_MSG;
7616 mHandler.sendMessage(msg);
7617 }
7618 } catch (RemoteException e) {
7619 }
7620
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007621 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007622 }
7623 }
7624
Dan Egnorb7f03672009-12-09 16:22:32 -08007625 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007626 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007628 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007629 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007630 startAppProblemLocked(app);
7631 app.stopFreezingAllLocked();
7632 return handleAppCrashLocked(app);
7633 }
7634
Dan Egnorb7f03672009-12-09 16:22:32 -08007635 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007636 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007637 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007638 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007639 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7640 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641 startAppProblemLocked(app);
7642 app.stopFreezingAllLocked();
7643 }
7644
7645 /**
7646 * Generate a process error record, suitable for attachment to a ProcessRecord.
7647 *
7648 * @param app The ProcessRecord in which the error occurred.
7649 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7650 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007651 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652 * @param shortMsg Short message describing the crash.
7653 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007654 * @param stackTrace Full crash stack trace, may be null.
7655 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007656 * @return Returns a fully-formed AppErrorStateInfo record.
7657 */
7658 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007659 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 report.condition = condition;
7663 report.processName = app.processName;
7664 report.pid = app.pid;
7665 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007666 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667 report.shortMsg = shortMsg;
7668 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007669 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670
7671 return report;
7672 }
7673
Dan Egnor42471dd2010-01-07 17:25:22 -08007674 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007675 synchronized (this) {
7676 app.crashing = false;
7677 app.crashingReport = null;
7678 app.notResponding = false;
7679 app.notRespondingReport = null;
7680 if (app.anrDialog == fromDialog) {
7681 app.anrDialog = null;
7682 }
7683 if (app.waitDialog == fromDialog) {
7684 app.waitDialog = null;
7685 }
7686 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007687 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007688 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007689 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7690 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007691 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007693 }
7694 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007695
Dan Egnorb7f03672009-12-09 16:22:32 -08007696 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007697 if (mHeadless) {
7698 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7699 return false;
7700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007701 long now = SystemClock.uptimeMillis();
7702
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007703 Long crashTime;
7704 if (!app.isolated) {
7705 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7706 } else {
7707 crashTime = null;
7708 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007709 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007711 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007713 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007714 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007715 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7716 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007717 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007718 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007719 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007720 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007721 }
7722 }
7723 if (!app.persistent) {
7724 // We don't want to start this process again until the user
7725 // explicitly does so... but for persistent process, we really
7726 // need to keep it running. If a persistent process is actually
7727 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007728 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007729 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007730 if (!app.isolated) {
7731 // XXX We don't have a way to mark isolated processes
7732 // as bad, since they don't have a peristent identity.
7733 mBadProcesses.put(app.info.processName, app.uid, now);
7734 mProcessCrashTimes.remove(app.info.processName, app.uid);
7735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007738 // Don't let services in this process be restarted and potentially
7739 // annoy the user repeatedly. Unless it is persistent, since those
7740 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007741 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007742 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007743 return false;
7744 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007745 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007746 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007747 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007748 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007749 // If the top running activity is from this crashing
7750 // process, then terminate it to avoid getting in a loop.
7751 Slog.w(TAG, " Force finishing activity "
7752 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007753 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007754 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007755 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007756 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007757 // stopped, to avoid a situation where one will get
7758 // re-start our crashing activity once it gets resumed again.
7759 index--;
7760 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007761 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007762 if (r.state == ActivityState.RESUMED
7763 || r.state == ActivityState.PAUSING
7764 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007765 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007766 Slog.w(TAG, " Force finishing activity "
7767 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007768 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007769 Activity.RESULT_CANCELED, null, "crashed");
7770 }
7771 }
7772 }
7773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007774 }
7775
7776 // Bump up the crash count of any services currently running in the proc.
7777 if (app.services.size() != 0) {
7778 // Any services running in the application need to be placed
7779 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007780 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007781 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007782 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 sr.crashCount++;
7784 }
7785 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007786
7787 // If the crashing process is what we consider to be the "home process" and it has been
7788 // replaced by a third-party app, clear the package preferred activities from packages
7789 // with a home activity running in the process to prevent a repeatedly crashing app
7790 // from blocking the user to manually clear the list.
7791 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7792 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7793 Iterator it = mHomeProcess.activities.iterator();
7794 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007795 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007796 if (r.isHomeActivity) {
7797 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7798 try {
7799 ActivityThread.getPackageManager()
7800 .clearPackagePreferredActivities(r.packageName);
7801 } catch (RemoteException c) {
7802 // pm is in same process, this will never happen.
7803 }
7804 }
7805 }
7806 }
7807
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007808 if (!app.isolated) {
7809 // XXX Can't keep track of crash times for isolated processes,
7810 // because they don't have a perisistent identity.
7811 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7812 }
7813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007814 return true;
7815 }
7816
7817 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007818 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7819 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007820 skipCurrentReceiverLocked(app);
7821 }
7822
7823 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007824 for (BroadcastQueue queue : mBroadcastQueues) {
7825 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 }
7827 }
7828
Dan Egnor60d87622009-12-16 16:32:58 -08007829 /**
7830 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7831 * The application process will exit immediately after this call returns.
7832 * @param app object of the crashing app, null for the system server
7833 * @param crashInfo describing the exception
7834 */
7835 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007836 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007837 final String processName = app == null ? "system_server"
7838 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007839
7840 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007841 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007842 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007843 crashInfo.exceptionClassName,
7844 crashInfo.exceptionMessage,
7845 crashInfo.throwFileName,
7846 crashInfo.throwLineNumber);
7847
Jeff Sharkeya353d262011-10-28 11:12:06 -07007848 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007849
7850 crashApplication(r, crashInfo);
7851 }
7852
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007853 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007854 IBinder app,
7855 int violationMask,
7856 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007857 ProcessRecord r = findAppProcess(app, "StrictMode");
7858 if (r == null) {
7859 return;
7860 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007861
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007862 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007863 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007864 boolean logIt = true;
7865 synchronized (mAlreadyLoggedViolatedStacks) {
7866 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7867 logIt = false;
7868 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007869 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007870 // the relative pain numbers, without logging all
7871 // the stack traces repeatedly. We'd want to do
7872 // likewise in the client code, which also does
7873 // dup suppression, before the Binder call.
7874 } else {
7875 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7876 mAlreadyLoggedViolatedStacks.clear();
7877 }
7878 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7879 }
7880 }
7881 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007882 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007883 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007884 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007885
7886 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7887 AppErrorResult result = new AppErrorResult();
7888 synchronized (this) {
7889 final long origId = Binder.clearCallingIdentity();
7890
7891 Message msg = Message.obtain();
7892 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7893 HashMap<String, Object> data = new HashMap<String, Object>();
7894 data.put("result", result);
7895 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007896 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007897 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007898 msg.obj = data;
7899 mHandler.sendMessage(msg);
7900
7901 Binder.restoreCallingIdentity(origId);
7902 }
7903 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007904 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007905 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007906 }
7907
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007908 // Depending on the policy in effect, there could be a bunch of
7909 // these in quick succession so we try to batch these together to
7910 // minimize disk writes, number of dropbox entries, and maximize
7911 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007912 private void logStrictModeViolationToDropBox(
7913 ProcessRecord process,
7914 StrictMode.ViolationInfo info) {
7915 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007916 return;
7917 }
7918 final boolean isSystemApp = process == null ||
7919 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7920 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007921 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007922 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7923 final DropBoxManager dbox = (DropBoxManager)
7924 mContext.getSystemService(Context.DROPBOX_SERVICE);
7925
7926 // Exit early if the dropbox isn't configured to accept this report type.
7927 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7928
7929 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007930 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007931 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7932 synchronized (sb) {
7933 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007934 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007935 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7936 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007937 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7938 if (info.violationNumThisLoop != 0) {
7939 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7940 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007941 if (info.numAnimationsRunning != 0) {
7942 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7943 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007944 if (info.broadcastIntentAction != null) {
7945 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7946 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007947 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007948 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007949 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007950 if (info.numInstances != -1) {
7951 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7952 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007953 if (info.tags != null) {
7954 for (String tag : info.tags) {
7955 sb.append("Span-Tag: ").append(tag).append("\n");
7956 }
7957 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007958 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007959 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7960 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007961 }
7962 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007963
7964 // Only buffer up to ~64k. Various logging bits truncate
7965 // things at 128k.
7966 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007967 }
7968
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007969 // Flush immediately if the buffer's grown too large, or this
7970 // is a non-system app. Non-system apps are isolated with a
7971 // different tag & policy and not batched.
7972 //
7973 // Batching is useful during internal testing with
7974 // StrictMode settings turned up high. Without batching,
7975 // thousands of separate files could be created on boot.
7976 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007977 new Thread("Error dump: " + dropboxTag) {
7978 @Override
7979 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007980 String report;
7981 synchronized (sb) {
7982 report = sb.toString();
7983 sb.delete(0, sb.length());
7984 sb.trimToSize();
7985 }
7986 if (report.length() != 0) {
7987 dbox.addText(dropboxTag, report);
7988 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007989 }
7990 }.start();
7991 return;
7992 }
7993
7994 // System app batching:
7995 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007996 // An existing dropbox-writing thread is outstanding, so
7997 // we don't need to start it up. The existing thread will
7998 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007999 return;
8000 }
8001
8002 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8003 // (After this point, we shouldn't access AMS internal data structures.)
8004 new Thread("Error dump: " + dropboxTag) {
8005 @Override
8006 public void run() {
8007 // 5 second sleep to let stacks arrive and be batched together
8008 try {
8009 Thread.sleep(5000); // 5 seconds
8010 } catch (InterruptedException e) {}
8011
8012 String errorReport;
8013 synchronized (mStrictModeBuffer) {
8014 errorReport = mStrictModeBuffer.toString();
8015 if (errorReport.length() == 0) {
8016 return;
8017 }
8018 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8019 mStrictModeBuffer.trimToSize();
8020 }
8021 dbox.addText(dropboxTag, errorReport);
8022 }
8023 }.start();
8024 }
8025
Dan Egnor60d87622009-12-16 16:32:58 -08008026 /**
8027 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8028 * @param app object of the crashing app, null for the system server
8029 * @param tag reported by the caller
8030 * @param crashInfo describing the context of the error
8031 * @return true if the process should exit immediately (WTF is fatal)
8032 */
8033 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008034 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008035 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008036 final String processName = app == null ? "system_server"
8037 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008038
8039 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008040 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008041 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008042 tag, crashInfo.exceptionMessage);
8043
Jeff Sharkeya353d262011-10-28 11:12:06 -07008044 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008045
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008046 if (r != null && r.pid != Process.myPid() &&
8047 Settings.Secure.getInt(mContext.getContentResolver(),
8048 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008049 crashApplication(r, crashInfo);
8050 return true;
8051 } else {
8052 return false;
8053 }
8054 }
8055
8056 /**
8057 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8058 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8059 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008060 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008061 if (app == null) {
8062 return null;
8063 }
8064
8065 synchronized (this) {
8066 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8067 final int NA = apps.size();
8068 for (int ia=0; ia<NA; ia++) {
8069 ProcessRecord p = apps.valueAt(ia);
8070 if (p.thread != null && p.thread.asBinder() == app) {
8071 return p;
8072 }
8073 }
8074 }
8075
Dianne Hackborncb44d962011-03-10 17:02:27 -08008076 Slog.w(TAG, "Can't find mystery application for " + reason
8077 + " from pid=" + Binder.getCallingPid()
8078 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008079 return null;
8080 }
8081 }
8082
8083 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008084 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8085 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008086 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008087 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8088 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008089 // Watchdog thread ends up invoking this function (with
8090 // a null ProcessRecord) to add the stack file to dropbox.
8091 // Do not acquire a lock on this (am) in such cases, as it
8092 // could cause a potential deadlock, if and when watchdog
8093 // is invoked due to unavailability of lock on am and it
8094 // would prevent watchdog from killing system_server.
8095 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008096 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008097 return;
8098 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008099 // Note: ProcessRecord 'process' is guarded by the service
8100 // instance. (notably process.pkgList, which could otherwise change
8101 // concurrently during execution of this method)
8102 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008103 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008104 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008105 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008106 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8107 for (String pkg : process.pkgList) {
8108 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008109 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008110 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008111 if (pi != null) {
8112 sb.append(" v").append(pi.versionCode);
8113 if (pi.versionName != null) {
8114 sb.append(" (").append(pi.versionName).append(")");
8115 }
8116 }
8117 } catch (RemoteException e) {
8118 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008119 }
Dan Egnora455d192010-03-12 08:52:28 -08008120 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008121 }
Dan Egnora455d192010-03-12 08:52:28 -08008122 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008123 }
8124
8125 private static String processClass(ProcessRecord process) {
8126 if (process == null || process.pid == MY_PID) {
8127 return "system_server";
8128 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8129 return "system_app";
8130 } else {
8131 return "data_app";
8132 }
8133 }
8134
8135 /**
8136 * Write a description of an error (crash, WTF, ANR) to the drop box.
8137 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8138 * @param process which caused the error, null means the system server
8139 * @param activity which triggered the error, null if unknown
8140 * @param parent activity related to the error, null if unknown
8141 * @param subject line related to the error, null if absent
8142 * @param report in long form describing the error, null if absent
8143 * @param logFile to include in the report, null if none
8144 * @param crashInfo giving an application stack trace, null if absent
8145 */
8146 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008147 ProcessRecord process, String processName, ActivityRecord activity,
8148 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008149 final String report, final File logFile,
8150 final ApplicationErrorReport.CrashInfo crashInfo) {
8151 // NOTE -- this must never acquire the ActivityManagerService lock,
8152 // otherwise the watchdog may be prevented from resetting the system.
8153
8154 final String dropboxTag = processClass(process) + "_" + eventType;
8155 final DropBoxManager dbox = (DropBoxManager)
8156 mContext.getSystemService(Context.DROPBOX_SERVICE);
8157
8158 // Exit early if the dropbox isn't configured to accept this report type.
8159 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8160
8161 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008162 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008163 if (activity != null) {
8164 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8165 }
8166 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8167 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8168 }
8169 if (parent != null && parent != activity) {
8170 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8171 }
8172 if (subject != null) {
8173 sb.append("Subject: ").append(subject).append("\n");
8174 }
8175 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008176 if (Debug.isDebuggerConnected()) {
8177 sb.append("Debugger: Connected\n");
8178 }
Dan Egnora455d192010-03-12 08:52:28 -08008179 sb.append("\n");
8180
8181 // Do the rest in a worker thread to avoid blocking the caller on I/O
8182 // (After this point, we shouldn't access AMS internal data structures.)
8183 Thread worker = new Thread("Error dump: " + dropboxTag) {
8184 @Override
8185 public void run() {
8186 if (report != null) {
8187 sb.append(report);
8188 }
8189 if (logFile != null) {
8190 try {
8191 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8192 } catch (IOException e) {
8193 Slog.e(TAG, "Error reading " + logFile, e);
8194 }
8195 }
8196 if (crashInfo != null && crashInfo.stackTrace != null) {
8197 sb.append(crashInfo.stackTrace);
8198 }
8199
8200 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8201 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8202 if (lines > 0) {
8203 sb.append("\n");
8204
8205 // Merge several logcat streams, and take the last N lines
8206 InputStreamReader input = null;
8207 try {
8208 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8209 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8210 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8211
8212 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8213 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8214 input = new InputStreamReader(logcat.getInputStream());
8215
8216 int num;
8217 char[] buf = new char[8192];
8218 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8219 } catch (IOException e) {
8220 Slog.e(TAG, "Error running logcat", e);
8221 } finally {
8222 if (input != null) try { input.close(); } catch (IOException e) {}
8223 }
8224 }
8225
8226 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008227 }
Dan Egnora455d192010-03-12 08:52:28 -08008228 };
8229
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008230 if (process == null) {
8231 // If process is null, we are being called from some internal code
8232 // and may be about to die -- run this synchronously.
8233 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008234 } else {
8235 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008236 }
8237 }
8238
8239 /**
8240 * Bring up the "unexpected error" dialog box for a crashing app.
8241 * Deal with edge cases (intercepts from instrumented applications,
8242 * ActivityController, error intent receivers, that sort of thing).
8243 * @param r the application crashing
8244 * @param crashInfo describing the failure
8245 */
8246 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008247 long timeMillis = System.currentTimeMillis();
8248 String shortMsg = crashInfo.exceptionClassName;
8249 String longMsg = crashInfo.exceptionMessage;
8250 String stackTrace = crashInfo.stackTrace;
8251 if (shortMsg != null && longMsg != null) {
8252 longMsg = shortMsg + ": " + longMsg;
8253 } else if (shortMsg != null) {
8254 longMsg = shortMsg;
8255 }
8256
Dan Egnor60d87622009-12-16 16:32:58 -08008257 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008258 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008259 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008260 try {
8261 String name = r != null ? r.processName : null;
8262 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008263 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008264 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008265 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008266 + " at watcher's request");
8267 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008268 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008269 }
8270 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008271 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008272 }
8273 }
8274
8275 final long origId = Binder.clearCallingIdentity();
8276
8277 // If this process is running instrumentation, finish it.
8278 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008279 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008280 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008281 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8282 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008283 Bundle info = new Bundle();
8284 info.putString("shortMsg", shortMsg);
8285 info.putString("longMsg", longMsg);
8286 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8287 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008288 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008289 }
8290
Dan Egnor60d87622009-12-16 16:32:58 -08008291 // If we can't identify the process or it's already exceeded its crash quota,
8292 // quit right away without showing a crash dialog.
8293 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008294 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008295 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296 }
8297
8298 Message msg = Message.obtain();
8299 msg.what = SHOW_ERROR_MSG;
8300 HashMap data = new HashMap();
8301 data.put("result", result);
8302 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008303 msg.obj = data;
8304 mHandler.sendMessage(msg);
8305
8306 Binder.restoreCallingIdentity(origId);
8307 }
8308
8309 int res = result.get();
8310
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008311 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008312 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008313 if (r != null && !r.isolated) {
8314 // XXX Can't keep track of crash time for isolated processes,
8315 // since they don't have a persistent identity.
8316 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008317 SystemClock.uptimeMillis());
8318 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008319 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008320 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008321 }
8322 }
8323
8324 if (appErrorIntent != null) {
8325 try {
8326 mContext.startActivity(appErrorIntent);
8327 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008328 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008331 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008332
8333 Intent createAppErrorIntentLocked(ProcessRecord r,
8334 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8335 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008336 if (report == null) {
8337 return null;
8338 }
8339 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8340 result.setComponent(r.errorReportReceiver);
8341 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8342 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8343 return result;
8344 }
8345
Dan Egnorb7f03672009-12-09 16:22:32 -08008346 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8347 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008348 if (r.errorReportReceiver == null) {
8349 return null;
8350 }
8351
8352 if (!r.crashing && !r.notResponding) {
8353 return null;
8354 }
8355
Dan Egnorb7f03672009-12-09 16:22:32 -08008356 ApplicationErrorReport report = new ApplicationErrorReport();
8357 report.packageName = r.info.packageName;
8358 report.installerPackageName = r.errorReportReceiver.getPackageName();
8359 report.processName = r.processName;
8360 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008361 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008362
Dan Egnorb7f03672009-12-09 16:22:32 -08008363 if (r.crashing) {
8364 report.type = ApplicationErrorReport.TYPE_CRASH;
8365 report.crashInfo = crashInfo;
8366 } else if (r.notResponding) {
8367 report.type = ApplicationErrorReport.TYPE_ANR;
8368 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008369
Dan Egnorb7f03672009-12-09 16:22:32 -08008370 report.anrInfo.activity = r.notRespondingReport.tag;
8371 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8372 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008373 }
8374
Dan Egnorb7f03672009-12-09 16:22:32 -08008375 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008376 }
8377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008378 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008379 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008380 // assume our apps are happy - lazy create the list
8381 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8382
8383 synchronized (this) {
8384
8385 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008386 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8387 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008388 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8389 // This one's in trouble, so we'll generate a report for it
8390 // crashes are higher priority (in case there's a crash *and* an anr)
8391 ActivityManager.ProcessErrorStateInfo report = null;
8392 if (app.crashing) {
8393 report = app.crashingReport;
8394 } else if (app.notResponding) {
8395 report = app.notRespondingReport;
8396 }
8397
8398 if (report != null) {
8399 if (errList == null) {
8400 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8401 }
8402 errList.add(report);
8403 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008404 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008405 " crashing = " + app.crashing +
8406 " notResponding = " + app.notResponding);
8407 }
8408 }
8409 }
8410 }
8411
8412 return errList;
8413 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008414
8415 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008416 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008417 if (currApp != null) {
8418 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8419 }
8420 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008421 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8422 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008423 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8424 if (currApp != null) {
8425 currApp.lru = 0;
8426 }
8427 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008428 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008429 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8430 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8431 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8432 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8433 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8434 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8435 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8436 } else {
8437 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8438 }
8439 }
8440
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008441 private void fillInProcMemInfo(ProcessRecord app,
8442 ActivityManager.RunningAppProcessInfo outInfo) {
8443 outInfo.pid = app.pid;
8444 outInfo.uid = app.info.uid;
8445 if (mHeavyWeightProcess == app) {
8446 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8447 }
8448 if (app.persistent) {
8449 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8450 }
8451 outInfo.lastTrimLevel = app.trimMemoryLevel;
8452 int adj = app.curAdj;
8453 outInfo.importance = oomAdjToImportance(adj, outInfo);
8454 outInfo.importanceReasonCode = app.adjTypeCode;
8455 }
8456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008457 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008458 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008459 // Lazy instantiation of list
8460 List<ActivityManager.RunningAppProcessInfo> runList = null;
8461 synchronized (this) {
8462 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008463 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8464 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008465 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8466 // Generate process state info for running application
8467 ActivityManager.RunningAppProcessInfo currApp =
8468 new ActivityManager.RunningAppProcessInfo(app.processName,
8469 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008470 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008471 if (app.adjSource instanceof ProcessRecord) {
8472 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008473 currApp.importanceReasonImportance = oomAdjToImportance(
8474 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008475 } else if (app.adjSource instanceof ActivityRecord) {
8476 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008477 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8478 }
8479 if (app.adjTarget instanceof ComponentName) {
8480 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8481 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008482 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008483 // + " lru=" + currApp.lru);
8484 if (runList == null) {
8485 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8486 }
8487 runList.add(currApp);
8488 }
8489 }
8490 }
8491 return runList;
8492 }
8493
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008494 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008495 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008496 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8497 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8498 if (runningApps != null && runningApps.size() > 0) {
8499 Set<String> extList = new HashSet<String>();
8500 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8501 if (app.pkgList != null) {
8502 for (String pkg : app.pkgList) {
8503 extList.add(pkg);
8504 }
8505 }
8506 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008507 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008508 for (String pkg : extList) {
8509 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008510 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008511 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8512 retList.add(info);
8513 }
8514 } catch (RemoteException e) {
8515 }
8516 }
8517 }
8518 return retList;
8519 }
8520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008521 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008522 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8523 enforceNotIsolatedCaller("getMyMemoryState");
8524 synchronized (this) {
8525 ProcessRecord proc;
8526 synchronized (mPidsSelfLocked) {
8527 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8528 }
8529 fillInProcMemInfo(proc, outInfo);
8530 }
8531 }
8532
8533 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008534 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008535 if (checkCallingPermission(android.Manifest.permission.DUMP)
8536 != PackageManager.PERMISSION_GRANTED) {
8537 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8538 + Binder.getCallingPid()
8539 + ", uid=" + Binder.getCallingUid()
8540 + " without permission "
8541 + android.Manifest.permission.DUMP);
8542 return;
8543 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008544
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008545 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008546 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008547 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008548
8549 int opti = 0;
8550 while (opti < args.length) {
8551 String opt = args[opti];
8552 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8553 break;
8554 }
8555 opti++;
8556 if ("-a".equals(opt)) {
8557 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008558 } else if ("-c".equals(opt)) {
8559 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008560 } else if ("-h".equals(opt)) {
8561 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008562 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008563 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008564 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008565 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8566 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8567 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008568 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008569 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008570 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008571 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008572 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008573 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008574 pw.println(" all: dump all activities");
8575 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008576 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008577 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8578 pw.println(" a partial substring in a component name, a");
8579 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008580 pw.println(" -a: include all available server state.");
8581 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008582 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008583 } else {
8584 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008585 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008586 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008587
8588 long origId = Binder.clearCallingIdentity();
8589 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008590 // Is the caller requesting to dump a particular piece of data?
8591 if (opti < args.length) {
8592 String cmd = args[opti];
8593 opti++;
8594 if ("activities".equals(cmd) || "a".equals(cmd)) {
8595 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008596 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008597 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008598 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008599 String[] newArgs;
8600 String name;
8601 if (opti >= args.length) {
8602 name = null;
8603 newArgs = EMPTY_STRING_ARRAY;
8604 } else {
8605 name = args[opti];
8606 opti++;
8607 newArgs = new String[args.length - opti];
8608 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8609 args.length - opti);
8610 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008611 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008612 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008613 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008614 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008615 String[] newArgs;
8616 String name;
8617 if (opti >= args.length) {
8618 name = null;
8619 newArgs = EMPTY_STRING_ARRAY;
8620 } else {
8621 name = args[opti];
8622 opti++;
8623 newArgs = new String[args.length - opti];
8624 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8625 args.length - opti);
8626 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008627 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008628 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008629 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008630 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008631 String[] newArgs;
8632 String name;
8633 if (opti >= args.length) {
8634 name = null;
8635 newArgs = EMPTY_STRING_ARRAY;
8636 } else {
8637 name = args[opti];
8638 opti++;
8639 newArgs = new String[args.length - opti];
8640 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8641 args.length - opti);
8642 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008643 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008644 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008645 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008646 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8647 synchronized (this) {
8648 dumpOomLocked(fd, pw, args, opti, true);
8649 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008650 } else if ("provider".equals(cmd)) {
8651 String[] newArgs;
8652 String name;
8653 if (opti >= args.length) {
8654 name = null;
8655 newArgs = EMPTY_STRING_ARRAY;
8656 } else {
8657 name = args[opti];
8658 opti++;
8659 newArgs = new String[args.length - opti];
8660 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8661 }
8662 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8663 pw.println("No providers match: " + name);
8664 pw.println("Use -h for help.");
8665 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008666 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8667 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008668 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008669 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008670 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008671 String[] newArgs;
8672 String name;
8673 if (opti >= args.length) {
8674 name = null;
8675 newArgs = EMPTY_STRING_ARRAY;
8676 } else {
8677 name = args[opti];
8678 opti++;
8679 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008680 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8681 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008682 }
8683 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8684 pw.println("No services match: " + name);
8685 pw.println("Use -h for help.");
8686 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008687 } else if ("package".equals(cmd)) {
8688 String[] newArgs;
8689 if (opti >= args.length) {
8690 pw.println("package: no package name specified");
8691 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008692 } else {
8693 dumpPackage = args[opti];
8694 opti++;
8695 newArgs = new String[args.length - opti];
8696 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8697 args.length - opti);
8698 args = newArgs;
8699 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008700 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008701 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008702 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8703 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008704 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008705 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008706 } else {
8707 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008708 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8709 pw.println("Bad activity command, or no activities match: " + cmd);
8710 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008711 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008712 }
8713 if (!more) {
8714 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008715 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008716 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008717 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008718
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008719 // No piece of data specified, dump everything.
8720 synchronized (this) {
8721 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008722 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008723 if (needSep) {
8724 pw.println(" ");
8725 }
8726 if (dumpAll) {
8727 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008728 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008729 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008730 if (needSep) {
8731 pw.println(" ");
8732 }
8733 if (dumpAll) {
8734 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008735 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008736 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008737 if (needSep) {
8738 pw.println(" ");
8739 }
8740 if (dumpAll) {
8741 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008742 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008743 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008744 if (needSep) {
8745 pw.println(" ");
8746 }
8747 if (dumpAll) {
8748 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008749 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008750 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008751 if (needSep) {
8752 pw.println(" ");
8753 }
8754 if (dumpAll) {
8755 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008756 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008757 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008758 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008759 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008760 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008761
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008762 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008763 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008764 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8765 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008766 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8767 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008768 pw.println(" ");
8769 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008770 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8771 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008772 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008773 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008774 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008775 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008776 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008777 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008778 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008779 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008780 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008781 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008782 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008783 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008784 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8785 pw.println(" ");
8786 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008787 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008788 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008789 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008790 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008791 pw.println(" ");
8792 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008793 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008794 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008796
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008797 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008798 if (mMainStack.mPausingActivity != null) {
8799 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008800 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008801 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008802 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008803 if (dumpAll) {
8804 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8805 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008806 pw.println(" mDismissKeyguardOnNextActivity: "
8807 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008809
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008810 if (mRecentTasks.size() > 0) {
8811 pw.println();
8812 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008813
8814 final int N = mRecentTasks.size();
8815 for (int i=0; i<N; i++) {
8816 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008817 if (dumpPackage != null) {
8818 if (tr.realActivity == null ||
8819 !dumpPackage.equals(tr.realActivity)) {
8820 continue;
8821 }
8822 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008823 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8824 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008825 if (dumpAll) {
8826 mRecentTasks.get(i).dump(pw, " ");
8827 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008828 }
8829 }
8830
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008831 if (dumpAll) {
8832 pw.println(" ");
8833 pw.println(" mCurTask: " + mCurTask);
8834 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008835
8836 return true;
8837 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008838
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008839 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008840 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008841 boolean needSep = false;
8842 int numPers = 0;
8843
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008844 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8845
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008846 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008847 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8848 final int NA = procs.size();
8849 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008850 ProcessRecord r = procs.valueAt(ia);
8851 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8852 continue;
8853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008854 if (!needSep) {
8855 pw.println(" All known processes:");
8856 needSep = true;
8857 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008858 pw.print(r.persistent ? " *PERS*" : " *APP*");
8859 pw.print(" UID "); pw.print(procs.keyAt(ia));
8860 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008861 r.dump(pw, " ");
8862 if (r.persistent) {
8863 numPers++;
8864 }
8865 }
8866 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008867 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008868
8869 if (mIsolatedProcesses.size() > 0) {
8870 if (needSep) pw.println(" ");
8871 needSep = true;
8872 pw.println(" Isolated process list (sorted by uid):");
8873 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8874 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8875 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8876 continue;
8877 }
8878 pw.println(String.format("%sIsolated #%2d: %s",
8879 " ", i, r.toString()));
8880 }
8881 }
8882
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008883 if (mLruProcesses.size() > 0) {
8884 if (needSep) pw.println(" ");
8885 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008886 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008887 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008888 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008889 needSep = true;
8890 }
8891
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008892 if (dumpAll) {
8893 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008894 boolean printed = false;
8895 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8896 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8897 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8898 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008899 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008900 if (!printed) {
8901 if (needSep) pw.println(" ");
8902 needSep = true;
8903 pw.println(" PID mappings:");
8904 printed = true;
8905 }
8906 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8907 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008908 }
8909 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008910 }
8911
8912 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008913 synchronized (mPidsSelfLocked) {
8914 boolean printed = false;
8915 for (int i=0; i<mForegroundProcesses.size(); i++) {
8916 ProcessRecord r = mPidsSelfLocked.get(
8917 mForegroundProcesses.valueAt(i).pid);
8918 if (dumpPackage != null && (r == null
8919 || !dumpPackage.equals(r.info.packageName))) {
8920 continue;
8921 }
8922 if (!printed) {
8923 if (needSep) pw.println(" ");
8924 needSep = true;
8925 pw.println(" Foreground Processes:");
8926 printed = true;
8927 }
8928 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8929 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008931 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008932 }
8933
8934 if (mPersistentStartingProcesses.size() > 0) {
8935 if (needSep) pw.println(" ");
8936 needSep = true;
8937 pw.println(" Persisent processes that are starting:");
8938 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008939 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008940 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008942 if (mRemovedProcesses.size() > 0) {
8943 if (needSep) pw.println(" ");
8944 needSep = true;
8945 pw.println(" Processes that are being removed:");
8946 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008947 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008948 }
8949
8950 if (mProcessesOnHold.size() > 0) {
8951 if (needSep) pw.println(" ");
8952 needSep = true;
8953 pw.println(" Processes that are on old until the system is ready:");
8954 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008955 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008958 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008959
8960 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008961 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008962 long now = SystemClock.uptimeMillis();
8963 for (Map.Entry<String, SparseArray<Long>> procs
8964 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008965 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008966 SparseArray<Long> uids = procs.getValue();
8967 final int N = uids.size();
8968 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008969 int puid = uids.keyAt(i);
8970 ProcessRecord r = mProcessNames.get(pname, puid);
8971 if (dumpPackage != null && (r == null
8972 || !dumpPackage.equals(r.info.packageName))) {
8973 continue;
8974 }
8975 if (!printed) {
8976 if (needSep) pw.println(" ");
8977 needSep = true;
8978 pw.println(" Time since processes crashed:");
8979 printed = true;
8980 }
8981 pw.print(" Process "); pw.print(pname);
8982 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008983 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008984 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8985 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008986 }
8987 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008989
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008990 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008991 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008992 for (Map.Entry<String, SparseArray<Long>> procs
8993 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008994 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008995 SparseArray<Long> uids = procs.getValue();
8996 final int N = uids.size();
8997 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008998 int puid = uids.keyAt(i);
8999 ProcessRecord r = mProcessNames.get(pname, puid);
9000 if (dumpPackage != null && (r == null
9001 || !dumpPackage.equals(r.info.packageName))) {
9002 continue;
9003 }
9004 if (!printed) {
9005 if (needSep) pw.println(" ");
9006 needSep = true;
9007 pw.println(" Bad processes:");
9008 }
9009 pw.print(" Bad process "); pw.print(pname);
9010 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009011 pw.print(": crashed at time ");
9012 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009013 }
9014 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009016
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009017 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009018 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009019 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009020 if (dumpAll) {
9021 StringBuilder sb = new StringBuilder(128);
9022 sb.append(" mPreviousProcessVisibleTime: ");
9023 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9024 pw.println(sb);
9025 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009026 if (mHeavyWeightProcess != null) {
9027 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9028 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009029 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009030 if (dumpAll) {
9031 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009032 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009033 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009034 for (Map.Entry<String, Integer> entry
9035 : mCompatModePackages.getPackages().entrySet()) {
9036 String pkg = entry.getKey();
9037 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009038 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9039 continue;
9040 }
9041 if (!printed) {
9042 pw.println(" mScreenCompatPackages:");
9043 printed = true;
9044 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009045 pw.print(" "); pw.print(pkg); pw.print(": ");
9046 pw.print(mode); pw.println();
9047 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009048 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009049 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009050 if (mSleeping || mWentToSleep || mLockScreenShown) {
9051 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9052 + " mLockScreenShown " + mLockScreenShown);
9053 }
9054 if (mShuttingDown) {
9055 pw.println(" mShuttingDown=" + mShuttingDown);
9056 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009057 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9058 || mOrigWaitForDebugger) {
9059 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9060 + " mDebugTransient=" + mDebugTransient
9061 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9062 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009063 if (mOpenGlTraceApp != null) {
9064 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9065 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009066 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9067 || mProfileFd != null) {
9068 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9069 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9070 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9071 + mAutoStopProfiler);
9072 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009073 if (mAlwaysFinishActivities || mController != null) {
9074 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9075 + " mController=" + mController);
9076 }
9077 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009079 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009080 + " mProcessesReady=" + mProcessesReady
9081 + " mSystemReady=" + mSystemReady);
9082 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009083 + " mBooted=" + mBooted
9084 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009085 pw.print(" mLastPowerCheckRealtime=");
9086 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9087 pw.println("");
9088 pw.print(" mLastPowerCheckUptime=");
9089 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9090 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009091 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9092 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009093 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009094 pw.println(" mNumServiceProcs=" + mNumServiceProcs
9095 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009096 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009097
9098 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009099 }
9100
Dianne Hackborn287952c2010-09-22 22:34:31 -07009101 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009102 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009103 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009104 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009105 long now = SystemClock.uptimeMillis();
9106 for (int i=0; i<mProcessesToGc.size(); i++) {
9107 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009108 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9109 continue;
9110 }
9111 if (!printed) {
9112 if (needSep) pw.println(" ");
9113 needSep = true;
9114 pw.println(" Processes that are waiting to GC:");
9115 printed = true;
9116 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009117 pw.print(" Process "); pw.println(proc);
9118 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9119 pw.print(", last gced=");
9120 pw.print(now-proc.lastRequestedGc);
9121 pw.print(" ms ago, last lowMem=");
9122 pw.print(now-proc.lastLowMemory);
9123 pw.println(" ms ago");
9124
9125 }
9126 }
9127 return needSep;
9128 }
9129
9130 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9131 int opti, boolean dumpAll) {
9132 boolean needSep = false;
9133
9134 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009135 if (needSep) pw.println(" ");
9136 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009137 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009138 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009139 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009140 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9141 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9142 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9143 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9144 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009145 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009146 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009147 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009148 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009149 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009150 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009151
9152 if (needSep) pw.println(" ");
9153 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009154 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009155 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009156 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009157 needSep = true;
9158 }
9159
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009160 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009161
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009162 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009163 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009164 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009165 if (mHeavyWeightProcess != null) {
9166 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9167 }
9168
9169 return true;
9170 }
9171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009172 /**
9173 * There are three ways to call this:
9174 * - no service specified: dump all the services
9175 * - a flattened component name that matched an existing service was specified as the
9176 * first arg: dump that one service
9177 * - the first arg isn't the flattened component name of an existing service:
9178 * dump all services whose component contains the first arg as a substring
9179 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009180 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9181 int opti, boolean dumpAll) {
9182 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009183
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009184 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009185 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009186 try {
9187 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9188 for (UserInfo user : users) {
9189 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9190 services.add(r1);
9191 }
9192 }
9193 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009194 }
9195 }
9196 } else {
9197 ComponentName componentName = name != null
9198 ? ComponentName.unflattenFromString(name) : null;
9199 int objectId = 0;
9200 if (componentName == null) {
9201 // Not a '/' separated full component name; maybe an object ID?
9202 try {
9203 objectId = Integer.parseInt(name, 16);
9204 name = null;
9205 componentName = null;
9206 } catch (RuntimeException e) {
9207 }
9208 }
9209
9210 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009211 try {
9212 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9213 for (UserInfo user : users) {
9214 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9215 if (componentName != null) {
9216 if (r1.name.equals(componentName)) {
9217 services.add(r1);
9218 }
9219 } else if (name != null) {
9220 if (r1.name.flattenToString().contains(name)) {
9221 services.add(r1);
9222 }
9223 } else if (System.identityHashCode(r1) == objectId) {
9224 services.add(r1);
9225 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009226 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009227 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009228 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009229 }
9230 }
9231 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009232
9233 if (services.size() <= 0) {
9234 return false;
9235 }
9236
9237 boolean needSep = false;
9238 for (int i=0; i<services.size(); i++) {
9239 if (needSep) {
9240 pw.println();
9241 }
9242 needSep = true;
9243 dumpService("", fd, pw, services.get(i), args, dumpAll);
9244 }
9245 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009246 }
9247
9248 /**
9249 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9250 * there is a thread associated with the service.
9251 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009252 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9253 final ServiceRecord r, String[] args, boolean dumpAll) {
9254 String innerPrefix = prefix + " ";
9255 synchronized (this) {
9256 pw.print(prefix); pw.print("SERVICE ");
9257 pw.print(r.shortName); pw.print(" ");
9258 pw.print(Integer.toHexString(System.identityHashCode(r)));
9259 pw.print(" pid=");
9260 if (r.app != null) pw.println(r.app.pid);
9261 else pw.println("(not running)");
9262 if (dumpAll) {
9263 r.dump(pw, innerPrefix);
9264 }
9265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009267 pw.print(prefix); pw.println(" Client:");
9268 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009269 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009270 TransferPipe tp = new TransferPipe();
9271 try {
9272 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9273 tp.setBufferPrefix(prefix + " ");
9274 tp.go(fd);
9275 } finally {
9276 tp.kill();
9277 }
9278 } catch (IOException e) {
9279 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009280 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009281 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009282 }
9283 }
9284 }
9285
Marco Nelissen18cb2872011-11-15 11:19:53 -08009286 /**
9287 * There are three ways to call this:
9288 * - no provider specified: dump all the providers
9289 * - a flattened component name that matched an existing provider was specified as the
9290 * first arg: dump that one provider
9291 * - the first arg isn't the flattened component name of an existing provider:
9292 * dump all providers whose component contains the first arg as a substring
9293 */
9294 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9295 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009296 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009297 }
9298
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009299 static class ItemMatcher {
9300 ArrayList<ComponentName> components;
9301 ArrayList<String> strings;
9302 ArrayList<Integer> objects;
9303 boolean all;
9304
9305 ItemMatcher() {
9306 all = true;
9307 }
9308
9309 void build(String name) {
9310 ComponentName componentName = ComponentName.unflattenFromString(name);
9311 if (componentName != null) {
9312 if (components == null) {
9313 components = new ArrayList<ComponentName>();
9314 }
9315 components.add(componentName);
9316 all = false;
9317 } else {
9318 int objectId = 0;
9319 // Not a '/' separated full component name; maybe an object ID?
9320 try {
9321 objectId = Integer.parseInt(name, 16);
9322 if (objects == null) {
9323 objects = new ArrayList<Integer>();
9324 }
9325 objects.add(objectId);
9326 all = false;
9327 } catch (RuntimeException e) {
9328 // Not an integer; just do string match.
9329 if (strings == null) {
9330 strings = new ArrayList<String>();
9331 }
9332 strings.add(name);
9333 all = false;
9334 }
9335 }
9336 }
9337
9338 int build(String[] args, int opti) {
9339 for (; opti<args.length; opti++) {
9340 String name = args[opti];
9341 if ("--".equals(name)) {
9342 return opti+1;
9343 }
9344 build(name);
9345 }
9346 return opti;
9347 }
9348
9349 boolean match(Object object, ComponentName comp) {
9350 if (all) {
9351 return true;
9352 }
9353 if (components != null) {
9354 for (int i=0; i<components.size(); i++) {
9355 if (components.get(i).equals(comp)) {
9356 return true;
9357 }
9358 }
9359 }
9360 if (objects != null) {
9361 for (int i=0; i<objects.size(); i++) {
9362 if (System.identityHashCode(object) == objects.get(i)) {
9363 return true;
9364 }
9365 }
9366 }
9367 if (strings != null) {
9368 String flat = comp.flattenToString();
9369 for (int i=0; i<strings.size(); i++) {
9370 if (flat.contains(strings.get(i))) {
9371 return true;
9372 }
9373 }
9374 }
9375 return false;
9376 }
9377 }
9378
Dianne Hackborn625ac272010-09-17 18:29:22 -07009379 /**
9380 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009381 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009382 * - the cmd arg isn't the flattened component name of an existing activity:
9383 * dump all activity whose component contains the cmd as a substring
9384 * - A hex number of the ActivityRecord object instance.
9385 */
9386 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9387 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009388 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009389
9390 if ("all".equals(name)) {
9391 synchronized (this) {
9392 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009393 activities.add(r1);
9394 }
9395 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009396 } else if ("top".equals(name)) {
9397 synchronized (this) {
9398 final int N = mMainStack.mHistory.size();
9399 if (N > 0) {
9400 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9401 }
9402 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009403 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009404 ItemMatcher matcher = new ItemMatcher();
9405 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009406
9407 synchronized (this) {
9408 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009409 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009410 activities.add(r1);
9411 }
9412 }
9413 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009414 }
9415
9416 if (activities.size() <= 0) {
9417 return false;
9418 }
9419
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009420 String[] newArgs = new String[args.length - opti];
9421 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9422
Dianne Hackborn30d71892010-12-11 10:37:55 -08009423 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009424 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009425 for (int i=activities.size()-1; i>=0; i--) {
9426 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009427 if (needSep) {
9428 pw.println();
9429 }
9430 needSep = true;
9431 synchronized (this) {
9432 if (lastTask != r.task) {
9433 lastTask = r.task;
9434 pw.print("TASK "); pw.print(lastTask.affinity);
9435 pw.print(" id="); pw.println(lastTask.taskId);
9436 if (dumpAll) {
9437 lastTask.dump(pw, " ");
9438 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009439 }
9440 }
9441 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009442 }
9443 return true;
9444 }
9445
9446 /**
9447 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9448 * there is a thread associated with the activity.
9449 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009450 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009451 final ActivityRecord r, String[] args, boolean dumpAll) {
9452 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009453 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009454 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9455 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9456 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009457 if (r.app != null) pw.println(r.app.pid);
9458 else pw.println("(not running)");
9459 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009460 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009461 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009462 }
9463 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009464 // flush anything that is already in the PrintWriter since the thread is going
9465 // to write to the file descriptor directly
9466 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009467 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009468 TransferPipe tp = new TransferPipe();
9469 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009470 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9471 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009472 tp.go(fd);
9473 } finally {
9474 tp.kill();
9475 }
9476 } catch (IOException e) {
9477 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009478 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009479 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009480 }
9481 }
9482 }
9483
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009484 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009485 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009486 boolean needSep = false;
9487
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009488 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009489 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009490 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009491 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009492 Iterator it = mRegisteredReceivers.values().iterator();
9493 while (it.hasNext()) {
9494 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009495 if (dumpPackage != null && (r.app == null ||
9496 !dumpPackage.equals(r.app.info.packageName))) {
9497 continue;
9498 }
9499 if (!printed) {
9500 pw.println(" Registered Receivers:");
9501 needSep = true;
9502 printed = true;
9503 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009504 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009505 r.dump(pw, " ");
9506 }
9507 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009508
9509 if (mReceiverResolver.dump(pw, needSep ?
9510 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9511 " ", dumpPackage, false)) {
9512 needSep = true;
9513 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009514 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009515
9516 for (BroadcastQueue q : mBroadcastQueues) {
9517 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009519
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009520 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009521
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009522 if (mStickyBroadcasts != null && dumpPackage == null) {
9523 if (needSep) {
9524 pw.println();
9525 }
9526 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009527 pw.println(" Sticky broadcasts:");
9528 StringBuilder sb = new StringBuilder(128);
9529 for (Map.Entry<String, ArrayList<Intent>> ent
9530 : mStickyBroadcasts.entrySet()) {
9531 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009532 if (dumpAll) {
9533 pw.println(":");
9534 ArrayList<Intent> intents = ent.getValue();
9535 final int N = intents.size();
9536 for (int i=0; i<N; i++) {
9537 sb.setLength(0);
9538 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009539 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009540 pw.println(sb.toString());
9541 Bundle bundle = intents.get(i).getExtras();
9542 if (bundle != null) {
9543 pw.print(" ");
9544 pw.println(bundle.toString());
9545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009546 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009547 } else {
9548 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009549 }
9550 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009551 needSep = true;
9552 }
9553
9554 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009555 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009556 for (BroadcastQueue queue : mBroadcastQueues) {
9557 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9558 + queue.mBroadcastsScheduled);
9559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009560 pw.println(" mHandler:");
9561 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009562 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009563 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009564
9565 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009566 }
9567
Marco Nelissen18cb2872011-11-15 11:19:53 -08009568 /**
9569 * Prints a list of ServiceRecords (dumpsys activity services)
9570 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009571 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009572 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009573 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009574
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009575 ItemMatcher matcher = new ItemMatcher();
9576 matcher.build(args, opti);
9577
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009578 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009579 try {
9580 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9581 for (UserInfo user : users) {
9582 if (mServiceMap.getAllServices(user.id).size() > 0) {
9583 boolean printed = false;
9584 long nowReal = SystemClock.elapsedRealtime();
9585 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9586 user.id).iterator();
9587 needSep = false;
9588 while (it.hasNext()) {
9589 ServiceRecord r = it.next();
9590 if (!matcher.match(r, r.name)) {
9591 continue;
9592 }
9593 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9594 continue;
9595 }
9596 if (!printed) {
9597 pw.println(" Active services:");
9598 printed = true;
9599 }
9600 if (needSep) {
9601 pw.println();
9602 }
9603 pw.print(" * ");
9604 pw.println(r);
9605 if (dumpAll) {
9606 r.dump(pw, " ");
9607 needSep = true;
9608 } else {
9609 pw.print(" app=");
9610 pw.println(r.app);
9611 pw.print(" created=");
9612 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9613 pw.print(" started=");
9614 pw.print(r.startRequested);
9615 pw.print(" connections=");
9616 pw.println(r.connections.size());
9617 if (r.connections.size() > 0) {
9618 pw.println(" Connections:");
9619 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9620 for (int i = 0; i < clist.size(); i++) {
9621 ConnectionRecord conn = clist.get(i);
9622 pw.print(" ");
9623 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009624 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009625 pw.print(" -> ");
9626 ProcessRecord proc = conn.binding.client;
9627 pw.println(proc != null ? proc.toShortString() : "null");
9628 }
9629 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009630 }
9631 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009632 if (dumpClient && r.app != null && r.app.thread != null) {
9633 pw.println(" Client:");
9634 pw.flush();
9635 try {
9636 TransferPipe tp = new TransferPipe();
9637 try {
9638 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9639 r, args);
9640 tp.setBufferPrefix(" ");
9641 // Short timeout, since blocking here can
9642 // deadlock with the application.
9643 tp.go(fd, 2000);
9644 } finally {
9645 tp.kill();
9646 }
9647 } catch (IOException e) {
9648 pw.println(" Failure while dumping the service: " + e);
9649 } catch (RemoteException e) {
9650 pw.println(" Got a RemoteException while dumping the service");
9651 }
9652 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009653 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009654 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009655 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009657 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009658 } catch (RemoteException re) {
9659
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009661
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009662 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009663 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009664 for (int i=0; i<mPendingServices.size(); i++) {
9665 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009666 if (!matcher.match(r, r.name)) {
9667 continue;
9668 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009669 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9670 continue;
9671 }
9672 if (!printed) {
9673 if (needSep) pw.println(" ");
9674 needSep = true;
9675 pw.println(" Pending services:");
9676 printed = true;
9677 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009678 pw.print(" * Pending "); pw.println(r);
9679 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009680 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009681 needSep = true;
9682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009683
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009684 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009685 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009686 for (int i=0; i<mRestartingServices.size(); i++) {
9687 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009688 if (!matcher.match(r, r.name)) {
9689 continue;
9690 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009691 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9692 continue;
9693 }
9694 if (!printed) {
9695 if (needSep) pw.println(" ");
9696 needSep = true;
9697 pw.println(" Restarting services:");
9698 printed = true;
9699 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009700 pw.print(" * Restarting "); pw.println(r);
9701 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009702 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009703 needSep = true;
9704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009705
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009706 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009707 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009708 for (int i=0; i<mStoppingServices.size(); i++) {
9709 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009710 if (!matcher.match(r, r.name)) {
9711 continue;
9712 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009713 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9714 continue;
9715 }
9716 if (!printed) {
9717 if (needSep) pw.println(" ");
9718 needSep = true;
9719 pw.println(" Stopping services:");
9720 printed = true;
9721 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009722 pw.print(" * Stopping "); pw.println(r);
9723 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009724 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009725 needSep = true;
9726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009727
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009728 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009729 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009730 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009731 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009732 = mServiceConnections.values().iterator();
9733 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009734 ArrayList<ConnectionRecord> r = it.next();
9735 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009736 ConnectionRecord cr = r.get(i);
9737 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9738 continue;
9739 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009740 if (dumpPackage != null && (cr.binding.client == null
9741 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9742 continue;
9743 }
9744 if (!printed) {
9745 if (needSep) pw.println(" ");
9746 needSep = true;
9747 pw.println(" Connection bindings to services:");
9748 printed = true;
9749 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009750 pw.print(" * "); pw.println(cr);
9751 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009753 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009754 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009755 }
9756 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009757
9758 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009759 }
9760
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009761 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009762 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009763 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009764
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009765 ItemMatcher matcher = new ItemMatcher();
9766 matcher.build(args, opti);
9767
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009768 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009769
9770 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009771
9772 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009773 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009774 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009775 ContentProviderRecord r = mLaunchingProviders.get(i);
9776 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9777 continue;
9778 }
9779 if (!printed) {
9780 if (needSep) pw.println(" ");
9781 needSep = true;
9782 pw.println(" Launching content providers:");
9783 printed = true;
9784 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009785 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009786 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009787 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009788 }
9789
9790 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009791 if (needSep) pw.println();
9792 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009793 pw.println("Granted Uri Permissions:");
9794 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9795 int uid = mGrantedUriPermissions.keyAt(i);
9796 HashMap<Uri, UriPermission> perms
9797 = mGrantedUriPermissions.valueAt(i);
9798 pw.print(" * UID "); pw.print(uid);
9799 pw.println(" holds:");
9800 for (UriPermission perm : perms.values()) {
9801 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009802 if (dumpAll) {
9803 perm.dump(pw, " ");
9804 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009805 }
9806 }
9807 needSep = true;
9808 }
9809
9810 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009811 }
9812
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009813 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009814 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009815 boolean needSep = false;
9816
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009817 if (mIntentSenderRecords.size() > 0) {
9818 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009819 Iterator<WeakReference<PendingIntentRecord>> it
9820 = mIntentSenderRecords.values().iterator();
9821 while (it.hasNext()) {
9822 WeakReference<PendingIntentRecord> ref = it.next();
9823 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009824 if (dumpPackage != null && (rec == null
9825 || !dumpPackage.equals(rec.key.packageName))) {
9826 continue;
9827 }
9828 if (!printed) {
9829 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9830 printed = true;
9831 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009832 needSep = true;
9833 if (rec != null) {
9834 pw.print(" * "); pw.println(rec);
9835 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009836 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009837 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009838 } else {
9839 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009840 }
9841 }
9842 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009843
9844 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009845 }
9846
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009847 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009848 String prefix, String label, boolean complete, boolean brief, boolean client,
9849 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009850 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009851 boolean needNL = false;
9852 final String innerPrefix = prefix + " ";
9853 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009854 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009855 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009856 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9857 continue;
9858 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009859 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009860 if (needNL) {
9861 pw.println(" ");
9862 needNL = false;
9863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009864 if (lastTask != r.task) {
9865 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009866 pw.print(prefix);
9867 pw.print(full ? "* " : " ");
9868 pw.println(lastTask);
9869 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009870 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009871 } else if (complete) {
9872 // Complete + brief == give a summary. Isn't that obvious?!?
9873 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009874 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009875 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009876 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009878 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009879 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9880 pw.print(" #"); pw.print(i); pw.print(": ");
9881 pw.println(r);
9882 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009883 r.dump(pw, innerPrefix);
9884 } else if (complete) {
9885 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009886 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009887 if (r.app != null) {
9888 pw.print(innerPrefix); pw.println(r.app);
9889 }
9890 }
9891 if (client && r.app != null && r.app.thread != null) {
9892 // flush anything that is already in the PrintWriter since the thread is going
9893 // to write to the file descriptor directly
9894 pw.flush();
9895 try {
9896 TransferPipe tp = new TransferPipe();
9897 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009898 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9899 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009900 // Short timeout, since blocking here can
9901 // deadlock with the application.
9902 tp.go(fd, 2000);
9903 } finally {
9904 tp.kill();
9905 }
9906 } catch (IOException e) {
9907 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9908 } catch (RemoteException e) {
9909 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9910 }
9911 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009913 }
9914 }
9915
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009916 private static String buildOomTag(String prefix, String space, int val, int base) {
9917 if (val == base) {
9918 if (space == null) return prefix;
9919 return prefix + " ";
9920 }
9921 return prefix + "+" + Integer.toString(val-base);
9922 }
9923
9924 private static final int dumpProcessList(PrintWriter pw,
9925 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009926 String prefix, String normalLabel, String persistentLabel,
9927 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009928 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009929 final int N = list.size()-1;
9930 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009931 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009932 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9933 continue;
9934 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009935 pw.println(String.format("%s%s #%2d: %s",
9936 prefix, (r.persistent ? persistentLabel : normalLabel),
9937 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009938 if (r.persistent) {
9939 numPers++;
9940 }
9941 }
9942 return numPers;
9943 }
9944
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009945 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009946 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009947 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009948 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009949
Dianne Hackborn905577f2011-09-07 18:31:28 -07009950 ArrayList<Pair<ProcessRecord, Integer>> list
9951 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9952 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009953 ProcessRecord r = origList.get(i);
9954 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9955 continue;
9956 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009957 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9958 }
9959
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009960 if (list.size() <= 0) {
9961 return false;
9962 }
9963
Dianne Hackborn905577f2011-09-07 18:31:28 -07009964 Comparator<Pair<ProcessRecord, Integer>> comparator
9965 = new Comparator<Pair<ProcessRecord, Integer>>() {
9966 @Override
9967 public int compare(Pair<ProcessRecord, Integer> object1,
9968 Pair<ProcessRecord, Integer> object2) {
9969 if (object1.first.setAdj != object2.first.setAdj) {
9970 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9971 }
9972 if (object1.second.intValue() != object2.second.intValue()) {
9973 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9974 }
9975 return 0;
9976 }
9977 };
9978
9979 Collections.sort(list, comparator);
9980
Dianne Hackborn287952c2010-09-22 22:34:31 -07009981 final long curRealtime = SystemClock.elapsedRealtime();
9982 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9983 final long curUptime = SystemClock.uptimeMillis();
9984 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9985
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009986 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009987 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009988 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009989 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009990 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009991 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9992 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009993 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9994 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009995 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9996 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009997 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9998 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009999 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010000 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010001 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10002 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10003 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10004 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10005 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10006 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10007 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10008 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010009 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10010 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010011 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10012 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010013 } else {
10014 oomAdj = Integer.toString(r.setAdj);
10015 }
10016 String schedGroup;
10017 switch (r.setSchedGroup) {
10018 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10019 schedGroup = "B";
10020 break;
10021 case Process.THREAD_GROUP_DEFAULT:
10022 schedGroup = "F";
10023 break;
10024 default:
10025 schedGroup = Integer.toString(r.setSchedGroup);
10026 break;
10027 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010028 String foreground;
10029 if (r.foregroundActivities) {
10030 foreground = "A";
10031 } else if (r.foregroundServices) {
10032 foreground = "S";
10033 } else {
10034 foreground = " ";
10035 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010036 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010037 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010038 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10039 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010040 if (r.adjSource != null || r.adjTarget != null) {
10041 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010042 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010043 if (r.adjTarget instanceof ComponentName) {
10044 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10045 } else if (r.adjTarget != null) {
10046 pw.print(r.adjTarget.toString());
10047 } else {
10048 pw.print("{null}");
10049 }
10050 pw.print("<=");
10051 if (r.adjSource instanceof ProcessRecord) {
10052 pw.print("Proc{");
10053 pw.print(((ProcessRecord)r.adjSource).toShortString());
10054 pw.println("}");
10055 } else if (r.adjSource != null) {
10056 pw.println(r.adjSource.toString());
10057 } else {
10058 pw.println("{null}");
10059 }
10060 }
10061 if (inclDetails) {
10062 pw.print(prefix);
10063 pw.print(" ");
10064 pw.print("oom: max="); pw.print(r.maxAdj);
10065 pw.print(" hidden="); pw.print(r.hiddenAdj);
10066 pw.print(" curRaw="); pw.print(r.curRawAdj);
10067 pw.print(" setRaw="); pw.print(r.setRawAdj);
10068 pw.print(" cur="); pw.print(r.curAdj);
10069 pw.print(" set="); pw.println(r.setAdj);
10070 pw.print(prefix);
10071 pw.print(" ");
10072 pw.print("keeping="); pw.print(r.keeping);
10073 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010074 pw.print(" empty="); pw.print(r.empty);
10075 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010076
10077 if (!r.keeping) {
10078 if (r.lastWakeTime != 0) {
10079 long wtime;
10080 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10081 synchronized (stats) {
10082 wtime = stats.getProcessWakeTime(r.info.uid,
10083 r.pid, curRealtime);
10084 }
10085 long timeUsed = wtime - r.lastWakeTime;
10086 pw.print(prefix);
10087 pw.print(" ");
10088 pw.print("keep awake over ");
10089 TimeUtils.formatDuration(realtimeSince, pw);
10090 pw.print(" used ");
10091 TimeUtils.formatDuration(timeUsed, pw);
10092 pw.print(" (");
10093 pw.print((timeUsed*100)/realtimeSince);
10094 pw.println("%)");
10095 }
10096 if (r.lastCpuTime != 0) {
10097 long timeUsed = r.curCpuTime - r.lastCpuTime;
10098 pw.print(prefix);
10099 pw.print(" ");
10100 pw.print("run cpu over ");
10101 TimeUtils.formatDuration(uptimeSince, pw);
10102 pw.print(" used ");
10103 TimeUtils.formatDuration(timeUsed, pw);
10104 pw.print(" (");
10105 pw.print((timeUsed*100)/uptimeSince);
10106 pw.println("%)");
10107 }
10108 }
10109 }
10110 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010111 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010112 }
10113
Dianne Hackbornb437e092011-08-05 17:50:29 -070010114 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010115 ArrayList<ProcessRecord> procs;
10116 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010117 if (args != null && args.length > start
10118 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010119 procs = new ArrayList<ProcessRecord>();
10120 int pid = -1;
10121 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010122 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010123 } catch (NumberFormatException e) {
10124
10125 }
10126 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10127 ProcessRecord proc = mLruProcesses.get(i);
10128 if (proc.pid == pid) {
10129 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010130 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010131 procs.add(proc);
10132 }
10133 }
10134 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010135 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010136 return null;
10137 }
10138 } else {
10139 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10140 }
10141 }
10142 return procs;
10143 }
10144
10145 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10146 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010147 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010148 if (procs == null) {
10149 return;
10150 }
10151
10152 long uptime = SystemClock.uptimeMillis();
10153 long realtime = SystemClock.elapsedRealtime();
10154 pw.println("Applications Graphics Acceleration Info:");
10155 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10156
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010157 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10158 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010159 if (r.thread != null) {
10160 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10161 pw.flush();
10162 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010163 TransferPipe tp = new TransferPipe();
10164 try {
10165 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10166 tp.go(fd);
10167 } finally {
10168 tp.kill();
10169 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010170 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010171 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010172 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010173 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010174 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010175 pw.flush();
10176 }
10177 }
10178 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010179 }
10180
Jeff Brown6754ba22011-12-14 20:20:01 -080010181 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10182 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10183 if (procs == null) {
10184 return;
10185 }
10186
10187 pw.println("Applications Database Info:");
10188
10189 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10190 ProcessRecord r = procs.get(i);
10191 if (r.thread != null) {
10192 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10193 pw.flush();
10194 try {
10195 TransferPipe tp = new TransferPipe();
10196 try {
10197 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10198 tp.go(fd);
10199 } finally {
10200 tp.kill();
10201 }
10202 } catch (IOException e) {
10203 pw.println("Failure while dumping the app: " + r);
10204 pw.flush();
10205 } catch (RemoteException e) {
10206 pw.println("Got a RemoteException while dumping the app " + r);
10207 pw.flush();
10208 }
10209 }
10210 }
10211 }
10212
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010213 final static class MemItem {
10214 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010215 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010216 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010217 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010218 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010219
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010220 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010221 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010222 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010223 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010224 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010225 }
10226 }
10227
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010228 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010229 boolean sort) {
10230 if (sort) {
10231 Collections.sort(items, new Comparator<MemItem>() {
10232 @Override
10233 public int compare(MemItem lhs, MemItem rhs) {
10234 if (lhs.pss < rhs.pss) {
10235 return 1;
10236 } else if (lhs.pss > rhs.pss) {
10237 return -1;
10238 }
10239 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010240 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010241 });
10242 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010243
10244 for (int i=0; i<items.size(); i++) {
10245 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010246 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010247 if (mi.subitems != null) {
10248 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10249 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010250 }
10251 }
10252
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010253 // These are in KB.
10254 static final long[] DUMP_MEM_BUCKETS = new long[] {
10255 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10256 120*1024, 160*1024, 200*1024,
10257 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10258 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10259 };
10260
Dianne Hackborn672342c2011-11-29 11:29:02 -080010261 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10262 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010263 int start = label.lastIndexOf('.');
10264 if (start >= 0) start++;
10265 else start = 0;
10266 int end = label.length();
10267 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10268 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10269 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10270 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010271 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010272 out.append(label, start, end);
10273 return;
10274 }
10275 }
10276 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010277 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010278 out.append(label, start, end);
10279 }
10280
10281 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10282 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10283 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10284 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10285 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10286 };
10287 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10288 "System", "Persistent", "Foreground",
10289 "Visible", "Perceptible", "Heavy Weight",
10290 "Backup", "A Services", "Home", "Previous",
10291 "B Services", "Background"
10292 };
10293
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010294 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010295 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010296 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010297 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010298 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010299
10300 int opti = 0;
10301 while (opti < args.length) {
10302 String opt = args[opti];
10303 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10304 break;
10305 }
10306 opti++;
10307 if ("-a".equals(opt)) {
10308 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010309 } else if ("--oom".equals(opt)) {
10310 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010311 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010312 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010313 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010314 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010315 pw.println("If [process] is specified it can be the name or ");
10316 pw.println("pid of a specific process to dump.");
10317 return;
10318 } else {
10319 pw.println("Unknown argument: " + opt + "; use -h for help");
10320 }
10321 }
10322
10323 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010324 if (procs == null) {
10325 return;
10326 }
10327
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010328 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010329 long uptime = SystemClock.uptimeMillis();
10330 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010331
10332 if (procs.size() == 1 || isCheckinRequest) {
10333 dumpAll = true;
10334 }
10335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010336 if (isCheckinRequest) {
10337 // short checkin version
10338 pw.println(uptime + "," + realtime);
10339 pw.flush();
10340 } else {
10341 pw.println("Applications Memory Usage (kB):");
10342 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10343 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010344
Dianne Hackbornb437e092011-08-05 17:50:29 -070010345 String[] innerArgs = new String[args.length-opti];
10346 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10347
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010348 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10349 long nativePss=0, dalvikPss=0, otherPss=0;
10350 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10351
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010352 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10353 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10354 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010355
10356 long totalPss = 0;
10357
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010358 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10359 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010360 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010361 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010362 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10363 pw.flush();
10364 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010365 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010366 if (dumpAll) {
10367 try {
10368 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10369 } catch (RemoteException e) {
10370 if (!isCheckinRequest) {
10371 pw.println("Got RemoteException!");
10372 pw.flush();
10373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010374 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010375 } else {
10376 mi = new Debug.MemoryInfo();
10377 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010378 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010379
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010380 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010381 long myTotalPss = mi.getTotalPss();
10382 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010383 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010384 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010385 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010386
10387 nativePss += mi.nativePss;
10388 dalvikPss += mi.dalvikPss;
10389 otherPss += mi.otherPss;
10390 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10391 long mem = mi.getOtherPss(j);
10392 miscPss[j] += mem;
10393 otherPss -= mem;
10394 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010395
10396 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010397 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10398 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010399 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010400 if (oomProcs[oomIndex] == null) {
10401 oomProcs[oomIndex] = new ArrayList<MemItem>();
10402 }
10403 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010404 break;
10405 }
10406 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010408 }
10409 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010410
10411 if (!isCheckinRequest && procs.size() > 1) {
10412 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10413
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010414 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10415 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10416 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010417 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010418 String label = Debug.MemoryInfo.getOtherLabel(j);
10419 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010420 }
10421
Dianne Hackbornb437e092011-08-05 17:50:29 -070010422 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10423 for (int j=0; j<oomPss.length; j++) {
10424 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010425 String label = DUMP_MEM_OOM_LABEL[j];
10426 MemItem item = new MemItem(label, label, oomPss[j],
10427 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010428 item.subitems = oomProcs[j];
10429 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010430 }
10431 }
10432
Dianne Hackborn672342c2011-11-29 11:29:02 -080010433 if (outTag != null || outStack != null) {
10434 if (outTag != null) {
10435 appendMemBucket(outTag, totalPss, "total", false);
10436 }
10437 if (outStack != null) {
10438 appendMemBucket(outStack, totalPss, "total", true);
10439 }
10440 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010441 for (int i=0; i<oomMems.size(); i++) {
10442 MemItem miCat = oomMems.get(i);
10443 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10444 continue;
10445 }
10446 if (miCat.id < ProcessList.SERVICE_ADJ
10447 || miCat.id == ProcessList.HOME_APP_ADJ
10448 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010449 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10450 outTag.append(" / ");
10451 }
10452 if (outStack != null) {
10453 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10454 if (firstLine) {
10455 outStack.append(":");
10456 firstLine = false;
10457 }
10458 outStack.append("\n\t at ");
10459 } else {
10460 outStack.append("$");
10461 }
10462 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010463 for (int j=0; j<miCat.subitems.size(); j++) {
10464 MemItem mi = miCat.subitems.get(j);
10465 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010466 if (outTag != null) {
10467 outTag.append(" ");
10468 }
10469 if (outStack != null) {
10470 outStack.append("$");
10471 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010472 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010473 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10474 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10475 }
10476 if (outStack != null) {
10477 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10478 }
10479 }
10480 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10481 outStack.append("(");
10482 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10483 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10484 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10485 outStack.append(":");
10486 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10487 }
10488 }
10489 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010490 }
10491 }
10492 }
10493 }
10494
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010495 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010496 pw.println();
10497 pw.println("Total PSS by process:");
10498 dumpMemItems(pw, " ", procMems, true);
10499 pw.println();
10500 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010501 pw.println("Total PSS by OOM adjustment:");
10502 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010503 if (!oomOnly) {
10504 PrintWriter out = categoryPw != null ? categoryPw : pw;
10505 out.println();
10506 out.println("Total PSS by category:");
10507 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010508 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010509 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010510 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010511 final int[] SINGLE_LONG_FORMAT = new int[] {
10512 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10513 };
10514 long[] longOut = new long[1];
10515 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10516 SINGLE_LONG_FORMAT, null, longOut, null);
10517 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10518 longOut[0] = 0;
10519 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10520 SINGLE_LONG_FORMAT, null, longOut, null);
10521 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10522 longOut[0] = 0;
10523 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10524 SINGLE_LONG_FORMAT, null, longOut, null);
10525 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10526 longOut[0] = 0;
10527 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10528 SINGLE_LONG_FORMAT, null, longOut, null);
10529 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10530 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10531 pw.print(shared); pw.println(" kB");
10532 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10533 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010535 }
10536
10537 /**
10538 * Searches array of arguments for the specified string
10539 * @param args array of argument strings
10540 * @param value value to search for
10541 * @return true if the value is contained in the array
10542 */
10543 private static boolean scanArgs(String[] args, String value) {
10544 if (args != null) {
10545 for (String arg : args) {
10546 if (value.equals(arg)) {
10547 return true;
10548 }
10549 }
10550 }
10551 return false;
10552 }
10553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010554 private final void killServicesLocked(ProcessRecord app,
10555 boolean allowRestart) {
10556 // Report disconnected services.
10557 if (false) {
10558 // XXX we are letting the client link to the service for
10559 // death notifications.
10560 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010561 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010562 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010563 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010564 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010565 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010566 = r.connections.values().iterator();
10567 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010568 ArrayList<ConnectionRecord> cl = jt.next();
10569 for (int i=0; i<cl.size(); i++) {
10570 ConnectionRecord c = cl.get(i);
10571 if (c.binding.client != app) {
10572 try {
10573 //c.conn.connected(r.className, null);
10574 } catch (Exception e) {
10575 // todo: this should be asynchronous!
10576 Slog.w(TAG, "Exception thrown disconnected servce "
10577 + r.shortName
10578 + " from app " + app.processName, e);
10579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010580 }
10581 }
10582 }
10583 }
10584 }
10585 }
10586 }
10587
10588 // Clean up any connections this application has to other services.
10589 if (app.connections.size() > 0) {
10590 Iterator<ConnectionRecord> it = app.connections.iterator();
10591 while (it.hasNext()) {
10592 ConnectionRecord r = it.next();
10593 removeConnectionLocked(r, app, null);
10594 }
10595 }
10596 app.connections.clear();
10597
10598 if (app.services.size() != 0) {
10599 // Any services running in the application need to be placed
10600 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010601 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010602 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010603 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010604 synchronized (sr.stats.getBatteryStats()) {
10605 sr.stats.stopLaunchedLocked();
10606 }
10607 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010608 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010609 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010610 if (mStoppingServices.remove(sr)) {
10611 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10612 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010613
10614 boolean hasClients = sr.bindings.size() > 0;
10615 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010616 Iterator<IntentBindRecord> bindings
10617 = sr.bindings.values().iterator();
10618 while (bindings.hasNext()) {
10619 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010620 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010621 + ": shouldUnbind=" + b.hasBound);
10622 b.binder = null;
10623 b.requested = b.received = b.hasBound = false;
10624 }
10625 }
10626
Dianne Hackborn070783f2010-12-29 16:46:28 -080010627 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10628 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010629 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010630 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010631 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010632 sr.crashCount, sr.shortName, app.pid);
10633 bringDownServiceLocked(sr, true);
10634 } else if (!allowRestart) {
10635 bringDownServiceLocked(sr, true);
10636 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010637 boolean canceled = scheduleServiceRestartLocked(sr, true);
10638
10639 // Should the service remain running? Note that in the
10640 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010641 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010642 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10643 if (sr.pendingStarts.size() == 0) {
10644 sr.startRequested = false;
10645 if (!hasClients) {
10646 // Whoops, no reason to restart!
10647 bringDownServiceLocked(sr, true);
10648 }
10649 }
10650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010651 }
10652 }
10653
10654 if (!allowRestart) {
10655 app.services.clear();
10656 }
10657 }
10658
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010659 // Make sure we have no more records on the stopping list.
10660 int i = mStoppingServices.size();
10661 while (i > 0) {
10662 i--;
10663 ServiceRecord sr = mStoppingServices.get(i);
10664 if (sr.app == app) {
10665 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010666 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010667 }
10668 }
10669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010670 app.executingServices.clear();
10671 }
10672
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010673 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10674 ContentProviderRecord cpr, boolean always) {
10675 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10676
10677 if (!inLaunching || always) {
10678 synchronized (cpr) {
10679 cpr.launchingApp = null;
10680 cpr.notifyAll();
10681 }
10682 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
10683 String names[] = cpr.info.authority.split(";");
10684 for (int j = 0; j < names.length; j++) {
10685 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010686 }
10687 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010688
10689 for (int i=0; i<cpr.connections.size(); i++) {
10690 ContentProviderConnection conn = cpr.connections.get(i);
10691 if (conn.waiting) {
10692 // If this connection is waiting for the provider, then we don't
10693 // need to mess with its process unless we are always removing
10694 // or for some reason the provider is not currently launching.
10695 if (inLaunching && !always) {
10696 continue;
10697 }
10698 }
10699 ProcessRecord capp = conn.client;
10700 conn.dead = true;
10701 if (conn.stableCount > 0) {
10702 if (!capp.persistent && capp.thread != null
10703 && capp.pid != 0
10704 && capp.pid != MY_PID) {
10705 Slog.i(TAG, "Kill " + capp.processName
10706 + " (pid " + capp.pid + "): provider " + cpr.info.name
10707 + " in dying process " + (proc != null ? proc.processName : "??"));
10708 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10709 capp.processName, capp.setAdj, "dying provider "
10710 + cpr.name.toShortString());
10711 Process.killProcessQuiet(capp.pid);
10712 }
10713 } else if (capp.thread != null && conn.provider.provider != null) {
10714 try {
10715 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10716 } catch (RemoteException e) {
10717 }
10718 // In the protocol here, we don't expect the client to correctly
10719 // clean up this connection, we'll just remove it.
10720 cpr.connections.remove(i);
10721 conn.client.conProviders.remove(conn);
10722 }
10723 }
10724
10725 if (inLaunching && always) {
10726 mLaunchingProviders.remove(cpr);
10727 }
10728 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010729 }
10730
10731 /**
10732 * Main code for cleaning up a process when it has gone away. This is
10733 * called both as a result of the process dying, or directly when stopping
10734 * a process when running in single process mode.
10735 */
10736 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010737 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010738 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010739 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010740 }
10741
Dianne Hackborn36124872009-10-08 16:22:03 -070010742 mProcessesToGc.remove(app);
10743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010744 // Dismiss any open dialogs.
10745 if (app.crashDialog != null) {
10746 app.crashDialog.dismiss();
10747 app.crashDialog = null;
10748 }
10749 if (app.anrDialog != null) {
10750 app.anrDialog.dismiss();
10751 app.anrDialog = null;
10752 }
10753 if (app.waitDialog != null) {
10754 app.waitDialog.dismiss();
10755 app.waitDialog = null;
10756 }
10757
10758 app.crashing = false;
10759 app.notResponding = false;
10760
10761 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010762 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010763 app.thread = null;
10764 app.forcingToForeground = null;
10765 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010766 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010767 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010768 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010769
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010770 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010771
10772 boolean restart = false;
10773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010774 // Remove published content providers.
10775 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010776 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010777 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010778 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010779
10780 final boolean always = app.bad || !allowRestart;
10781 if (removeDyingProviderLocked(app, cpr, always) || always) {
10782 // We left the provider in the launching list, need to
10783 // restart it.
10784 restart = true;
10785 }
10786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010787 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010788 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010789 }
10790 app.pubProviders.clear();
10791 }
10792
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010793 // Take care of any launching providers waiting for this process.
10794 if (checkAppInLaunchingProvidersLocked(app, false)) {
10795 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010796 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010798 // Unregister from connected content providers.
10799 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010800 for (int i=0; i<app.conProviders.size(); i++) {
10801 ContentProviderConnection conn = app.conProviders.get(i);
10802 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010803 }
10804 app.conProviders.clear();
10805 }
10806
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010807 // At this point there may be remaining entries in mLaunchingProviders
10808 // where we were the only one waiting, so they are no longer of use.
10809 // Look for these and clean up if found.
10810 // XXX Commented out for now. Trying to figure out a way to reproduce
10811 // the actual situation to identify what is actually going on.
10812 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010813 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010814 ContentProviderRecord cpr = (ContentProviderRecord)
10815 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010816 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010817 synchronized (cpr) {
10818 cpr.launchingApp = null;
10819 cpr.notifyAll();
10820 }
10821 }
10822 }
10823 }
10824
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 skipCurrentReceiverLocked(app);
10826
10827 // Unregister any receivers.
10828 if (app.receivers.size() > 0) {
10829 Iterator<ReceiverList> it = app.receivers.iterator();
10830 while (it.hasNext()) {
10831 removeReceiverLocked(it.next());
10832 }
10833 app.receivers.clear();
10834 }
10835
Christopher Tate181fafa2009-05-14 11:12:14 -070010836 // If the app is undergoing backup, tell the backup manager about it
10837 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010838 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010839 try {
10840 IBackupManager bm = IBackupManager.Stub.asInterface(
10841 ServiceManager.getService(Context.BACKUP_SERVICE));
10842 bm.agentDisconnected(app.info.packageName);
10843 } catch (RemoteException e) {
10844 // can't happen; backup manager is local
10845 }
10846 }
10847
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010848 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10849 ProcessChangeItem item = mPendingProcessChanges.get(i);
10850 if (item.pid == app.pid) {
10851 mPendingProcessChanges.remove(i);
10852 mAvailProcessChanges.add(item);
10853 }
10854 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010855 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010857 // If the caller is restarting this app, then leave it in its
10858 // current lists and let the caller take care of it.
10859 if (restarting) {
10860 return;
10861 }
10862
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010863 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010864 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010865 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010866 mProcessNames.remove(app.processName, app.uid);
10867 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010868 if (mHeavyWeightProcess == app) {
10869 mHeavyWeightProcess = null;
10870 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010872 } else if (!app.removed) {
10873 // This app is persistent, so we need to keep its record around.
10874 // If it is not already on the pending app list, add it there
10875 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010876 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10877 mPersistentStartingProcesses.add(app);
10878 restart = true;
10879 }
10880 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010881 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10882 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010883 mProcessesOnHold.remove(app);
10884
The Android Open Source Project4df24232009-03-05 14:34:35 -080010885 if (app == mHomeProcess) {
10886 mHomeProcess = null;
10887 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010888 if (app == mPreviousProcess) {
10889 mPreviousProcess = null;
10890 }
10891
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010892 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010893 // We have components that still need to be running in the
10894 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010895 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010896 startProcessLocked(app, "restart", app.processName);
10897 } else if (app.pid > 0 && app.pid != MY_PID) {
10898 // Goodbye!
10899 synchronized (mPidsSelfLocked) {
10900 mPidsSelfLocked.remove(app.pid);
10901 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10902 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010903 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010904 }
10905 }
10906
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010907 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10908 // Look through the content providers we are waiting to have launched,
10909 // and if any run in this process then either schedule a restart of
10910 // the process or kill the client waiting for it if this process has
10911 // gone bad.
10912 int NL = mLaunchingProviders.size();
10913 boolean restart = false;
10914 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010915 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010916 if (cpr.launchingApp == app) {
10917 if (!alwaysBad && !app.bad) {
10918 restart = true;
10919 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010920 removeDyingProviderLocked(app, cpr, true);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010921 NL = mLaunchingProviders.size();
10922 }
10923 }
10924 }
10925 return restart;
10926 }
10927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010928 // =========================================================
10929 // SERVICES
10930 // =========================================================
10931
10932 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10933 ActivityManager.RunningServiceInfo info =
10934 new ActivityManager.RunningServiceInfo();
10935 info.service = r.name;
10936 if (r.app != null) {
10937 info.pid = r.app.pid;
10938 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010939 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010940 info.process = r.processName;
10941 info.foreground = r.isForeground;
10942 info.activeSince = r.createTime;
10943 info.started = r.startRequested;
10944 info.clientCount = r.connections.size();
10945 info.crashCount = r.crashCount;
10946 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010947 if (r.isForeground) {
10948 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10949 }
10950 if (r.startRequested) {
10951 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10952 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010953 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010954 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10955 }
10956 if (r.app != null && r.app.persistent) {
10957 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10958 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010959
10960 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10961 for (int i=0; i<connl.size(); i++) {
10962 ConnectionRecord conn = connl.get(i);
10963 if (conn.clientLabel != 0) {
10964 info.clientPackage = conn.binding.client.info.packageName;
10965 info.clientLabel = conn.clientLabel;
10966 return info;
10967 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010968 }
10969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010970 return info;
10971 }
10972
10973 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10974 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010975 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010976 synchronized (this) {
10977 ArrayList<ActivityManager.RunningServiceInfo> res
10978 = new ArrayList<ActivityManager.RunningServiceInfo>();
10979
Amith Yamasani742a6712011-05-04 14:49:28 -070010980 int userId = UserId.getUserId(Binder.getCallingUid());
10981 if (mServiceMap.getAllServices(userId).size() > 0) {
10982 Iterator<ServiceRecord> it
10983 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010984 while (it.hasNext() && res.size() < maxNum) {
10985 res.add(makeRunningServiceInfoLocked(it.next()));
10986 }
10987 }
10988
10989 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10990 ServiceRecord r = mRestartingServices.get(i);
10991 ActivityManager.RunningServiceInfo info =
10992 makeRunningServiceInfoLocked(r);
10993 info.restarting = r.nextRestartTime;
10994 res.add(info);
10995 }
10996
10997 return res;
10998 }
10999 }
11000
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011001 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011002 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011003 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011004 int userId = UserId.getUserId(Binder.getCallingUid());
11005 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011006 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011007 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
11008 for (int i=0; i<conn.size(); i++) {
11009 if (conn.get(i).clientIntent != null) {
11010 return conn.get(i).clientIntent;
11011 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011012 }
11013 }
11014 }
11015 }
11016 return null;
11017 }
11018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011019 private final ServiceRecord findServiceLocked(ComponentName name,
11020 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011021 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011022 return r == token ? r : null;
11023 }
11024
11025 private final class ServiceLookupResult {
11026 final ServiceRecord record;
11027 final String permission;
11028
11029 ServiceLookupResult(ServiceRecord _record, String _permission) {
11030 record = _record;
11031 permission = _permission;
11032 }
11033 };
11034
11035 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011036 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011037 ServiceRecord r = null;
11038 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011039 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011040 }
11041 if (r == null) {
11042 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070011043 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011044 }
11045
11046 if (r == null) {
11047 try {
11048 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011049 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011050 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011051 ServiceInfo sInfo =
11052 rInfo != null ? rInfo.serviceInfo : null;
11053 if (sInfo == null) {
11054 return null;
11055 }
11056
11057 ComponentName name = new ComponentName(
11058 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070011059 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011060 } catch (RemoteException ex) {
11061 // pm is in same process, this will never happen.
11062 }
11063 }
11064 if (r != null) {
11065 int callingPid = Binder.getCallingPid();
11066 int callingUid = Binder.getCallingUid();
11067 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011068 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011069 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011070 if (!r.exported) {
11071 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11072 + " from pid=" + callingPid
11073 + ", uid=" + callingUid
11074 + " that is not exported from uid " + r.appInfo.uid);
11075 return new ServiceLookupResult(null, "not exported from uid "
11076 + r.appInfo.uid);
11077 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011078 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011079 + " from pid=" + callingPid
11080 + ", uid=" + callingUid
11081 + " requires " + r.permission);
11082 return new ServiceLookupResult(null, r.permission);
11083 }
11084 return new ServiceLookupResult(r, null);
11085 }
11086 return null;
11087 }
11088
11089 private class ServiceRestarter implements Runnable {
11090 private ServiceRecord mService;
11091
11092 void setService(ServiceRecord service) {
11093 mService = service;
11094 }
11095
11096 public void run() {
11097 synchronized(ActivityManagerService.this) {
11098 performServiceRestartLocked(mService);
11099 }
11100 }
11101 }
11102
11103 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011104 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011105 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070011106 if (DEBUG_SERVICE)
11107 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011108 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070011109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011110 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011111 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011112 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011113 if (r == null) {
11114 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011115 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070011116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011117 if (r == null) {
11118 try {
11119 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011120 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011121 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011122 ServiceInfo sInfo =
11123 rInfo != null ? rInfo.serviceInfo : null;
11124 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011125 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011126 ": not found");
11127 return null;
11128 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011129 if (userId > 0) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070011130 if (isSingleton(sInfo.processName, sInfo.applicationInfo)) {
11131 userId = 0;
11132 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011133 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070011134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011135 ComponentName name = new ComponentName(
11136 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011137 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011138 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011139 Intent.FilterComparison filter = new Intent.FilterComparison(
11140 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011141 ServiceRestarter res = new ServiceRestarter();
11142 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11143 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11144 synchronized (stats) {
11145 ss = stats.getServiceStatsLocked(
11146 sInfo.applicationInfo.uid, sInfo.packageName,
11147 sInfo.name);
11148 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080011149 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011150 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070011151 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
11152 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011153
11154 // Make sure this component isn't in the pending list.
11155 int N = mPendingServices.size();
11156 for (int i=0; i<N; i++) {
11157 ServiceRecord pr = mPendingServices.get(i);
11158 if (pr.name.equals(name)) {
11159 mPendingServices.remove(i);
11160 i--;
11161 N--;
11162 }
11163 }
11164 }
11165 } catch (RemoteException ex) {
11166 // pm is in same process, this will never happen.
11167 }
11168 }
11169 if (r != null) {
11170 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011171 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011172 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011173 if (!r.exported) {
11174 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11175 + " from pid=" + callingPid
11176 + ", uid=" + callingUid
11177 + " that is not exported from uid " + r.appInfo.uid);
11178 return new ServiceLookupResult(null, "not exported from uid "
11179 + r.appInfo.uid);
11180 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011181 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011182 + " from pid=" + callingPid
11183 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011184 + " requires " + r.permission);
11185 return new ServiceLookupResult(null, r.permission);
11186 }
11187 return new ServiceLookupResult(r, null);
11188 }
11189 return null;
11190 }
11191
Dianne Hackborn287952c2010-09-22 22:34:31 -070011192 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
11193 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11194 + why + " of " + r + " in app " + r.app);
11195 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11196 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011197 long now = SystemClock.uptimeMillis();
11198 if (r.executeNesting == 0 && r.app != null) {
11199 if (r.app.executingServices.size() == 0) {
11200 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11201 msg.obj = r.app;
11202 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11203 }
11204 r.app.executingServices.add(r);
11205 }
11206 r.executeNesting++;
11207 r.executingStart = now;
11208 }
11209
11210 private final void sendServiceArgsLocked(ServiceRecord r,
11211 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011212 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011213 if (N == 0) {
11214 return;
11215 }
11216
Dianne Hackborn39792d22010-08-19 18:01:52 -070011217 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011218 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011219 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011220 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11221 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011222 if (si.intent == null && N > 1) {
11223 // If somehow we got a dummy null intent in the middle,
11224 // then skip it. DO NOT skip a null intent when it is
11225 // the only one in the list -- this is to support the
11226 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011227 continue;
11228 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011229 si.deliveredTime = SystemClock.uptimeMillis();
11230 r.deliveredStarts.add(si);
11231 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011232 if (si.neededGrants != null) {
11233 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
11234 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011235 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011236 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011237 if (!oomAdjusted) {
11238 oomAdjusted = true;
11239 updateOomAdjLocked(r.app);
11240 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011241 int flags = 0;
Dianne Hackbornd8f10242012-05-08 17:14:58 -070011242 if (si.deliveryCount > 1) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011243 flags |= Service.START_FLAG_RETRY;
11244 }
11245 if (si.doneExecutingCount > 0) {
11246 flags |= Service.START_FLAG_REDELIVERY;
11247 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011248 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011249 } catch (RemoteException e) {
11250 // Remote process gone... we'll let the normal cleanup take
11251 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011252 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011253 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011254 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011255 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256 break;
11257 }
11258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011259 }
11260
11261 private final boolean requestServiceBindingLocked(ServiceRecord r,
11262 IntentBindRecord i, boolean rebind) {
11263 if (r.app == null || r.app.thread == null) {
11264 // If service is not currently running, can't yet bind.
11265 return false;
11266 }
11267 if ((!i.requested || rebind) && i.apps.size() > 0) {
11268 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011269 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011270 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11271 if (!rebind) {
11272 i.requested = true;
11273 }
11274 i.hasBound = true;
11275 i.doRebind = false;
11276 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011277 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011278 return false;
11279 }
11280 }
11281 return true;
11282 }
11283
11284 private final void requestServiceBindingsLocked(ServiceRecord r) {
11285 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11286 while (bindings.hasNext()) {
11287 IntentBindRecord i = bindings.next();
11288 if (!requestServiceBindingLocked(r, i, false)) {
11289 break;
11290 }
11291 }
11292 }
11293
11294 private final void realStartServiceLocked(ServiceRecord r,
11295 ProcessRecord app) throws RemoteException {
11296 if (app.thread == null) {
11297 throw new RemoteException();
11298 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011299 if (DEBUG_MU)
11300 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011301 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011302 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011303 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011304
11305 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011306 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011307 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011308
11309 boolean created = false;
11310 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011311 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011312 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011313 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011314 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011315 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011316 synchronized (r.stats.getBatteryStats()) {
11317 r.stats.startLaunchedLocked();
11318 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011319 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011320 app.thread.scheduleCreateService(r, r.serviceInfo,
11321 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011322 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011323 created = true;
11324 } finally {
11325 if (!created) {
11326 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011327 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011328 }
11329 }
11330
11331 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011332
11333 // If the service is in the started state, and there are no
11334 // pending arguments, then fake up one so its onStartCommand() will
11335 // be called.
11336 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011337 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011338 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011339 }
11340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011341 sendServiceArgsLocked(r, true);
11342 }
11343
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011344 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11345 boolean allowCancel) {
11346 boolean canceled = false;
11347
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011348 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011349 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011350 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011351
Dianne Hackborn070783f2010-12-29 16:46:28 -080011352 if ((r.serviceInfo.applicationInfo.flags
11353 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11354 minDuration /= 4;
11355 }
11356
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011357 // Any delivered but not yet finished starts should be put back
11358 // on the pending list.
11359 final int N = r.deliveredStarts.size();
11360 if (N > 0) {
11361 for (int i=N-1; i>=0; i--) {
11362 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011363 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011364 if (si.intent == null) {
11365 // We'll generate this again if needed.
11366 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11367 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11368 r.pendingStarts.add(0, si);
11369 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11370 dur *= 2;
11371 if (minDuration < dur) minDuration = dur;
11372 if (resetTime < dur) resetTime = dur;
11373 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011374 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011375 + r.name);
11376 canceled = true;
11377 }
11378 }
11379 r.deliveredStarts.clear();
11380 }
11381
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011382 r.totalRestartCount++;
11383 if (r.restartDelay == 0) {
11384 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011385 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011386 } else {
11387 // If it has been a "reasonably long time" since the service
11388 // was started, then reset our restart duration back to
11389 // the beginning, so we don't infinitely increase the duration
11390 // on a service that just occasionally gets killed (which is
11391 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011392 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011393 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011394 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011395 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011396 if ((r.serviceInfo.applicationInfo.flags
11397 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11398 // Services in peristent processes will restart much more
11399 // quickly, since they are pretty important. (Think SystemUI).
11400 r.restartDelay += minDuration/2;
11401 } else {
11402 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11403 if (r.restartDelay < minDuration) {
11404 r.restartDelay = minDuration;
11405 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011407 }
11408 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011409
11410 r.nextRestartTime = now + r.restartDelay;
11411
11412 // Make sure that we don't end up restarting a bunch of services
11413 // all at the same time.
11414 boolean repeat;
11415 do {
11416 repeat = false;
11417 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11418 ServiceRecord r2 = mRestartingServices.get(i);
11419 if (r2 != r && r.nextRestartTime
11420 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11421 && r.nextRestartTime
11422 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11423 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11424 r.restartDelay = r.nextRestartTime - now;
11425 repeat = true;
11426 break;
11427 }
11428 }
11429 } while (repeat);
11430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011431 if (!mRestartingServices.contains(r)) {
11432 mRestartingServices.add(r);
11433 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011434
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011435 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011437 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011438 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011439 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011440 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011441 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011442 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011443 r.shortName, r.restartDelay);
11444
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011445 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011446 }
11447
11448 final void performServiceRestartLocked(ServiceRecord r) {
11449 if (!mRestartingServices.contains(r)) {
11450 return;
11451 }
11452 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11453 }
11454
11455 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11456 if (r.restartDelay == 0) {
11457 return false;
11458 }
11459 r.resetRestartCounter();
11460 mRestartingServices.remove(r);
11461 mHandler.removeCallbacks(r.restarter);
11462 return true;
11463 }
11464
11465 private final boolean bringUpServiceLocked(ServiceRecord r,
11466 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011467 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011468 //r.dump(" ");
11469
Dianne Hackborn36124872009-10-08 16:22:03 -070011470 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011471 sendServiceArgsLocked(r, false);
11472 return true;
11473 }
11474
11475 if (!whileRestarting && r.restartDelay > 0) {
11476 // If waiting for a restart, then do nothing.
11477 return true;
11478 }
11479
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011480 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011481
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011482 // We are now bringing the service up, so no longer in the
11483 // restarting state.
11484 mRestartingServices.remove(r);
11485
Dianne Hackborne7f97212011-02-24 14:40:20 -080011486 // Service is now being launched, its package can't be stopped.
11487 try {
11488 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011489 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011490 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011491 } catch (IllegalArgumentException e) {
11492 Slog.w(TAG, "Failed trying to unstop package "
11493 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011494 }
11495
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011496 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011497 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011498 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011499
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011500 if (!isolated) {
11501 app = getProcessRecordLocked(appName, r.appInfo.uid);
11502 if (DEBUG_MU)
11503 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11504 if (app != null && app.thread != null) {
11505 try {
11506 app.addPackage(r.appInfo.packageName);
11507 realStartServiceLocked(r, app);
11508 return true;
11509 } catch (RemoteException e) {
11510 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11511 }
11512
11513 // If a dead object exception was thrown -- fall through to
11514 // restart the application.
11515 }
11516 } else {
11517 // If this service runs in an isolated process, then each time
11518 // we call startProcessLocked() we will get a new isolated
11519 // process, starting another process if we are currently waiting
11520 // for a previous process to come up. To deal with this, we store
11521 // in the service any current isolated process it is running in or
11522 // waiting to have come up.
11523 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011524 }
11525
Dianne Hackborn36124872009-10-08 16:22:03 -070011526 // Not running -- get it started, and enqueue this service record
11527 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011528 if (app == null) {
11529 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11530 "service", r.name, false, isolated)) == null) {
11531 Slog.w(TAG, "Unable to launch app "
11532 + r.appInfo.packageName + "/"
11533 + r.appInfo.uid + " for service "
11534 + r.intent.getIntent() + ": process is bad");
11535 bringDownServiceLocked(r, true);
11536 return false;
11537 }
11538 if (isolated) {
11539 r.isolatedProc = app;
11540 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011541 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011543 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011544 mPendingServices.add(r);
11545 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011547 return true;
11548 }
11549
11550 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011551 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011552 //r.dump(" ");
11553
11554 // Does it still need to run?
11555 if (!force && r.startRequested) {
11556 return;
11557 }
11558 if (r.connections.size() > 0) {
11559 if (!force) {
11560 // XXX should probably keep a count of the number of auto-create
11561 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011562 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011563 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011564 ArrayList<ConnectionRecord> cr = it.next();
11565 for (int i=0; i<cr.size(); i++) {
11566 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11567 return;
11568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011569 }
11570 }
11571 }
11572
11573 // Report to all of the connections that the service is no longer
11574 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011575 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011576 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011577 ArrayList<ConnectionRecord> c = it.next();
11578 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011579 ConnectionRecord cr = c.get(i);
11580 // There is still a connection to the service that is
11581 // being brought down. Mark it as dead.
11582 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011583 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011584 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011585 } catch (Exception e) {
11586 Slog.w(TAG, "Failure disconnecting service " + r.name +
11587 " to connection " + c.get(i).conn.asBinder() +
11588 " (in " + c.get(i).binding.client.processName + ")", e);
11589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011590 }
11591 }
11592 }
11593
11594 // Tell the service that it has been unbound.
11595 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11596 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11597 while (it.hasNext()) {
11598 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011599 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011600 + ": hasBound=" + ibr.hasBound);
11601 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11602 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011603 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011604 updateOomAdjLocked(r.app);
11605 ibr.hasBound = false;
11606 r.app.thread.scheduleUnbindService(r,
11607 ibr.intent.getIntent());
11608 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011609 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011610 + r.shortName, e);
11611 serviceDoneExecutingLocked(r, true);
11612 }
11613 }
11614 }
11615 }
11616
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011617 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011618 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011619 System.identityHashCode(r), r.shortName,
11620 (r.app != null) ? r.app.pid : -1);
11621
Amith Yamasani742a6712011-05-04 14:49:28 -070011622 mServiceMap.removeServiceByName(r.name, r.userId);
11623 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011624 r.totalRestartCount = 0;
11625 unscheduleServiceRestartLocked(r);
11626
11627 // Also make sure it is not on the pending list.
11628 int N = mPendingServices.size();
11629 for (int i=0; i<N; i++) {
11630 if (mPendingServices.get(i) == r) {
11631 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011632 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011633 i--;
11634 N--;
11635 }
11636 }
11637
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011638 r.cancelNotification();
11639 r.isForeground = false;
11640 r.foregroundId = 0;
11641 r.foregroundNoti = null;
11642
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011643 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011644 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011645 r.pendingStarts.clear();
11646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011647 if (r.app != null) {
11648 synchronized (r.stats.getBatteryStats()) {
11649 r.stats.stopLaunchedLocked();
11650 }
11651 r.app.services.remove(r);
11652 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011653 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011654 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011655 mStoppingServices.add(r);
11656 updateOomAdjLocked(r.app);
11657 r.app.thread.scheduleStopService(r);
11658 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011659 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011660 + r.shortName, e);
11661 serviceDoneExecutingLocked(r, true);
11662 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011663 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011664 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011665 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011666 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011667 }
11668 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011669 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011670 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011671 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011672
11673 if (r.bindings.size() > 0) {
11674 r.bindings.clear();
11675 }
11676
11677 if (r.restarter instanceof ServiceRestarter) {
11678 ((ServiceRestarter)r.restarter).setService(null);
11679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011680 }
11681
11682 ComponentName startServiceLocked(IApplicationThread caller,
11683 Intent service, String resolvedType,
11684 int callingPid, int callingUid) {
11685 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011686 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011687 + " type=" + resolvedType + " args=" + service.getExtras());
11688
11689 if (caller != null) {
11690 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11691 if (callerApp == null) {
11692 throw new SecurityException(
11693 "Unable to find app for caller " + caller
11694 + " (pid=" + Binder.getCallingPid()
11695 + ") when starting service " + service);
11696 }
11697 }
11698
11699 ServiceLookupResult res =
11700 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011701 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011702 if (res == null) {
11703 return null;
11704 }
11705 if (res.record == null) {
11706 return new ComponentName("!", res.permission != null
11707 ? res.permission : "private to package");
11708 }
11709 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011710 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11711 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011712 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011713 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011714 }
11715 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011716 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011717 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011718 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011719 r.lastActivity = SystemClock.uptimeMillis();
11720 synchronized (r.stats.getBatteryStats()) {
11721 r.stats.startRunningLocked();
11722 }
11723 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11724 return new ComponentName("!", "Service process is bad");
11725 }
11726 return r.name;
11727 }
11728 }
11729
11730 public ComponentName startService(IApplicationThread caller, Intent service,
11731 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011732 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011733 // Refuse possible leaked file descriptors
11734 if (service != null && service.hasFileDescriptors() == true) {
11735 throw new IllegalArgumentException("File descriptors passed in Intent");
11736 }
11737
Amith Yamasani742a6712011-05-04 14:49:28 -070011738 if (DEBUG_SERVICE)
11739 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011740 synchronized(this) {
11741 final int callingPid = Binder.getCallingPid();
11742 final int callingUid = Binder.getCallingUid();
11743 final long origId = Binder.clearCallingIdentity();
11744 ComponentName res = startServiceLocked(caller, service,
11745 resolvedType, callingPid, callingUid);
11746 Binder.restoreCallingIdentity(origId);
11747 return res;
11748 }
11749 }
11750
11751 ComponentName startServiceInPackage(int uid,
11752 Intent service, String resolvedType) {
11753 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011754 if (DEBUG_SERVICE)
11755 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011756 final long origId = Binder.clearCallingIdentity();
11757 ComponentName res = startServiceLocked(null, service,
11758 resolvedType, -1, uid);
11759 Binder.restoreCallingIdentity(origId);
11760 return res;
11761 }
11762 }
11763
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011764 private void stopServiceLocked(ServiceRecord service) {
11765 synchronized (service.stats.getBatteryStats()) {
11766 service.stats.stopRunningLocked();
11767 }
11768 service.startRequested = false;
11769 service.callStart = false;
11770 bringDownServiceLocked(service, false);
11771 }
11772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011773 public int stopService(IApplicationThread caller, Intent service,
11774 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011775 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011776 // Refuse possible leaked file descriptors
11777 if (service != null && service.hasFileDescriptors() == true) {
11778 throw new IllegalArgumentException("File descriptors passed in Intent");
11779 }
11780
11781 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011782 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011783 + " type=" + resolvedType);
11784
11785 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11786 if (caller != null && callerApp == null) {
11787 throw new SecurityException(
11788 "Unable to find app for caller " + caller
11789 + " (pid=" + Binder.getCallingPid()
11790 + ") when stopping service " + service);
11791 }
11792
11793 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011794 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11795 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011796 if (r != null) {
11797 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011798 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011799 try {
11800 stopServiceLocked(r.record);
11801 } finally {
11802 Binder.restoreCallingIdentity(origId);
11803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011804 return 1;
11805 }
11806 return -1;
11807 }
11808 }
11809
11810 return 0;
11811 }
11812
11813 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011814 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011815 // Refuse possible leaked file descriptors
11816 if (service != null && service.hasFileDescriptors() == true) {
11817 throw new IllegalArgumentException("File descriptors passed in Intent");
11818 }
11819
11820 IBinder ret = null;
11821
11822 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011823 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11824 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011825
11826 if (r != null) {
11827 // r.record is null if findServiceLocked() failed the caller permission check
11828 if (r.record == null) {
11829 throw new SecurityException(
11830 "Permission Denial: Accessing service " + r.record.name
11831 + " from pid=" + Binder.getCallingPid()
11832 + ", uid=" + Binder.getCallingUid()
11833 + " requires " + r.permission);
11834 }
11835 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11836 if (ib != null) {
11837 ret = ib.binder;
11838 }
11839 }
11840 }
11841
11842 return ret;
11843 }
11844
11845 public boolean stopServiceToken(ComponentName className, IBinder token,
11846 int startId) {
11847 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011848 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011849 + " " + token + " startId=" + startId);
11850 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011851 if (r != null) {
11852 if (startId >= 0) {
11853 // Asked to only stop if done with all work. Note that
11854 // to avoid leaks, we will take this as dropping all
11855 // start items up to and including this one.
11856 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11857 if (si != null) {
11858 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011859 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11860 cur.removeUriPermissionsLocked();
11861 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011862 break;
11863 }
11864 }
11865 }
11866
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011867 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011868 return false;
11869 }
11870
11871 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011872 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011873 + " is last, but have " + r.deliveredStarts.size()
11874 + " remaining args");
11875 }
11876 }
11877
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011878 synchronized (r.stats.getBatteryStats()) {
11879 r.stats.stopRunningLocked();
11880 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011881 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011882 }
11883 final long origId = Binder.clearCallingIdentity();
11884 bringDownServiceLocked(r, false);
11885 Binder.restoreCallingIdentity(origId);
11886 return true;
11887 }
11888 }
11889 return false;
11890 }
11891
11892 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011893 int id, Notification notification, boolean removeNotification) {
11894 final long origId = Binder.clearCallingIdentity();
11895 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896 synchronized(this) {
11897 ServiceRecord r = findServiceLocked(className, token);
11898 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011899 if (id != 0) {
11900 if (notification == null) {
11901 throw new IllegalArgumentException("null notification");
11902 }
11903 if (r.foregroundId != id) {
11904 r.cancelNotification();
11905 r.foregroundId = id;
11906 }
11907 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11908 r.foregroundNoti = notification;
11909 r.isForeground = true;
11910 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011911 if (r.app != null) {
11912 updateServiceForegroundLocked(r.app, true);
11913 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011914 } else {
11915 if (r.isForeground) {
11916 r.isForeground = false;
11917 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011918 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011919 updateServiceForegroundLocked(r.app, true);
11920 }
11921 }
11922 if (removeNotification) {
11923 r.cancelNotification();
11924 r.foregroundId = 0;
11925 r.foregroundNoti = null;
11926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011927 }
11928 }
11929 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011930 } finally {
11931 Binder.restoreCallingIdentity(origId);
11932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011933 }
11934
11935 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11936 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011937 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011938 if (sr.isForeground) {
11939 anyForeground = true;
11940 break;
11941 }
11942 }
11943 if (anyForeground != proc.foregroundServices) {
11944 proc.foregroundServices = anyForeground;
11945 if (oomAdj) {
11946 updateOomAdjLocked();
11947 }
11948 }
11949 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011950
11951 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo) {
11952 boolean result = false;
11953 if (UserId.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
11954 result = false;
11955 } else if (componentProcessName == aInfo.packageName) {
11956 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11957 } else if ("system".equals(componentProcessName)) {
11958 result = true;
11959 }
11960 if (DEBUG_MU) {
11961 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo + ") = " + result);
11962 }
11963 return result;
11964 }
11965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011966 public int bindService(IApplicationThread caller, IBinder token,
11967 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011968 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011969 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011970 // Refuse possible leaked file descriptors
11971 if (service != null && service.hasFileDescriptors() == true) {
11972 throw new IllegalArgumentException("File descriptors passed in Intent");
11973 }
11974
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011975 checkValidCaller(Binder.getCallingUid(), userId);
11976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011977 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011978 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011979 + " type=" + resolvedType + " conn=" + connection.asBinder()
11980 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011981 if (DEBUG_MU)
11982 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11983 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11985 if (callerApp == null) {
11986 throw new SecurityException(
11987 "Unable to find app for caller " + caller
11988 + " (pid=" + Binder.getCallingPid()
11989 + ") when binding service " + service);
11990 }
11991
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011992 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011993 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011994 activity = mMainStack.isInStackLocked(token);
11995 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011996 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011997 return 0;
11998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011999 }
12000
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012001 int clientLabel = 0;
12002 PendingIntent clientIntent = null;
12003
12004 if (callerApp.info.uid == Process.SYSTEM_UID) {
12005 // Hacky kind of thing -- allow system stuff to tell us
12006 // what they are, so we can report this elsewhere for
12007 // others to know why certain services are running.
12008 try {
12009 clientIntent = (PendingIntent)service.getParcelableExtra(
12010 Intent.EXTRA_CLIENT_INTENT);
12011 } catch (RuntimeException e) {
12012 }
12013 if (clientIntent != null) {
12014 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
12015 if (clientLabel != 0) {
12016 // There are no useful extras in the intent, trash them.
12017 // System code calling with this stuff just needs to know
12018 // this will happen.
12019 service = service.cloneFilter();
12020 }
12021 }
12022 }
12023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012024 ServiceLookupResult res =
12025 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080012026 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012027 if (res == null) {
12028 return 0;
12029 }
12030 if (res.record == null) {
12031 return -1;
12032 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070012033 if (isSingleton(res.record.processName, res.record.appInfo)) {
12034 userId = 0;
12035 res = retrieveServiceLocked(service, resolvedType, Binder.getCallingPid(),
12036 Binder.getCallingUid(), 0);
12037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012038 ServiceRecord s = res.record;
12039
12040 final long origId = Binder.clearCallingIdentity();
12041
12042 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012043 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012044 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012045 }
12046
12047 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
12048 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012049 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012050
12051 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012052 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12053 if (clist == null) {
12054 clist = new ArrayList<ConnectionRecord>();
12055 s.connections.put(binder, clist);
12056 }
12057 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012058 b.connections.add(c);
12059 if (activity != null) {
12060 if (activity.connections == null) {
12061 activity.connections = new HashSet<ConnectionRecord>();
12062 }
12063 activity.connections.add(c);
12064 }
12065 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012066 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12067 b.client.hasAboveClient = true;
12068 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012069 clist = mServiceConnections.get(binder);
12070 if (clist == null) {
12071 clist = new ArrayList<ConnectionRecord>();
12072 mServiceConnections.put(binder, clist);
12073 }
12074 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075
12076 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
12077 s.lastActivity = SystemClock.uptimeMillis();
12078 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
12079 return 0;
12080 }
12081 }
12082
12083 if (s.app != null) {
12084 // This could have made the service more important.
12085 updateOomAdjLocked(s.app);
12086 }
12087
Joe Onorato8a9b2202010-02-26 18:56:32 -080012088 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012089 + ": received=" + b.intent.received
12090 + " apps=" + b.intent.apps.size()
12091 + " doRebind=" + b.intent.doRebind);
12092
12093 if (s.app != null && b.intent.received) {
12094 // Service is already running, so we can immediately
12095 // publish the connection.
12096 try {
12097 c.conn.connected(s.name, b.intent.binder);
12098 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012099 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012100 + " to connection " + c.conn.asBinder()
12101 + " (in " + c.binding.client.processName + ")", e);
12102 }
12103
12104 // If this is the first app connected back to this binding,
12105 // and the service had previously asked to be told when
12106 // rebound, then do so.
12107 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
12108 requestServiceBindingLocked(s, b.intent, true);
12109 }
12110 } else if (!b.intent.requested) {
12111 requestServiceBindingLocked(s, b.intent, false);
12112 }
12113
12114 Binder.restoreCallingIdentity(origId);
12115 }
12116
12117 return 1;
12118 }
12119
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012120 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012121 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012122 IBinder binder = c.conn.asBinder();
12123 AppBindRecord b = c.binding;
12124 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012125 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12126 if (clist != null) {
12127 clist.remove(c);
12128 if (clist.size() == 0) {
12129 s.connections.remove(binder);
12130 }
12131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012132 b.connections.remove(c);
12133 if (c.activity != null && c.activity != skipAct) {
12134 if (c.activity.connections != null) {
12135 c.activity.connections.remove(c);
12136 }
12137 }
12138 if (b.client != skipApp) {
12139 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012140 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12141 b.client.updateHasAboveClientLocked();
12142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012143 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012144 clist = mServiceConnections.get(binder);
12145 if (clist != null) {
12146 clist.remove(c);
12147 if (clist.size() == 0) {
12148 mServiceConnections.remove(binder);
12149 }
12150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012151
12152 if (b.connections.size() == 0) {
12153 b.intent.apps.remove(b.client);
12154 }
12155
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012156 if (!c.serviceDead) {
12157 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
12158 + ": shouldUnbind=" + b.intent.hasBound);
12159 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
12160 && b.intent.hasBound) {
12161 try {
12162 bumpServiceExecutingLocked(s, "unbind");
12163 updateOomAdjLocked(s.app);
12164 b.intent.hasBound = false;
12165 // Assume the client doesn't want to know about a rebind;
12166 // we will deal with that later if it asks for one.
12167 b.intent.doRebind = false;
12168 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
12169 } catch (Exception e) {
12170 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
12171 serviceDoneExecutingLocked(s, true);
12172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012173 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012174
12175 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
12176 bringDownServiceLocked(s, false);
12177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012178 }
12179 }
12180
12181 public boolean unbindService(IServiceConnection connection) {
12182 synchronized (this) {
12183 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012184 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012185 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
12186 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012187 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012188 + connection.asBinder());
12189 return false;
12190 }
12191
12192 final long origId = Binder.clearCallingIdentity();
12193
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012194 while (clist.size() > 0) {
12195 ConnectionRecord r = clist.get(0);
12196 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012197
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012198 if (r.binding.service.app != null) {
12199 // This could have made the service less important.
12200 updateOomAdjLocked(r.binding.service.app);
12201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012202 }
12203
12204 Binder.restoreCallingIdentity(origId);
12205 }
12206
12207 return true;
12208 }
12209
12210 public void publishService(IBinder token, Intent intent, IBinder service) {
12211 // Refuse possible leaked file descriptors
12212 if (intent != null && intent.hasFileDescriptors() == true) {
12213 throw new IllegalArgumentException("File descriptors passed in Intent");
12214 }
12215
12216 synchronized(this) {
12217 if (!(token instanceof ServiceRecord)) {
12218 throw new IllegalArgumentException("Invalid service token");
12219 }
12220 ServiceRecord r = (ServiceRecord)token;
12221
12222 final long origId = Binder.clearCallingIdentity();
12223
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012224 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012225 + " " + intent + ": " + service);
12226 if (r != null) {
12227 Intent.FilterComparison filter
12228 = new Intent.FilterComparison(intent);
12229 IntentBindRecord b = r.bindings.get(filter);
12230 if (b != null && !b.received) {
12231 b.binder = service;
12232 b.requested = true;
12233 b.received = true;
12234 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012235 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012236 = r.connections.values().iterator();
12237 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012238 ArrayList<ConnectionRecord> clist = it.next();
12239 for (int i=0; i<clist.size(); i++) {
12240 ConnectionRecord c = clist.get(i);
12241 if (!filter.equals(c.binding.intent.intent)) {
12242 if (DEBUG_SERVICE) Slog.v(
12243 TAG, "Not publishing to: " + c);
12244 if (DEBUG_SERVICE) Slog.v(
12245 TAG, "Bound intent: " + c.binding.intent.intent);
12246 if (DEBUG_SERVICE) Slog.v(
12247 TAG, "Published intent: " + intent);
12248 continue;
12249 }
12250 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12251 try {
12252 c.conn.connected(r.name, service);
12253 } catch (Exception e) {
12254 Slog.w(TAG, "Failure sending service " + r.name +
12255 " to connection " + c.conn.asBinder() +
12256 " (in " + c.binding.client.processName + ")", e);
12257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012258 }
12259 }
12260 }
12261 }
12262
12263 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12264
12265 Binder.restoreCallingIdentity(origId);
12266 }
12267 }
12268 }
12269
12270 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12271 // Refuse possible leaked file descriptors
12272 if (intent != null && intent.hasFileDescriptors() == true) {
12273 throw new IllegalArgumentException("File descriptors passed in Intent");
12274 }
12275
12276 synchronized(this) {
12277 if (!(token instanceof ServiceRecord)) {
12278 throw new IllegalArgumentException("Invalid service token");
12279 }
12280 ServiceRecord r = (ServiceRecord)token;
12281
12282 final long origId = Binder.clearCallingIdentity();
12283
12284 if (r != null) {
12285 Intent.FilterComparison filter
12286 = new Intent.FilterComparison(intent);
12287 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012288 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012289 + " at " + b + ": apps="
12290 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012291
12292 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012293 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012294 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012295 // Applications have already bound since the last
12296 // unbind, so just rebind right here.
12297 requestServiceBindingLocked(r, b, true);
12298 } else {
12299 // Note to tell the service the next time there is
12300 // a new client.
12301 b.doRebind = true;
12302 }
12303 }
12304
Per Edelberg78f9fff2010-08-30 20:01:35 +020012305 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012306
12307 Binder.restoreCallingIdentity(origId);
12308 }
12309 }
12310 }
12311
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012312 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012313 synchronized(this) {
12314 if (!(token instanceof ServiceRecord)) {
12315 throw new IllegalArgumentException("Invalid service token");
12316 }
12317 ServiceRecord r = (ServiceRecord)token;
12318 boolean inStopping = mStoppingServices.contains(token);
12319 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012320 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012321 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012322 + " with incorrect token: given " + token
12323 + ", expected " + r);
12324 return;
12325 }
12326
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012327 if (type == 1) {
12328 // This is a call from a service start... take care of
12329 // book-keeping.
12330 r.callStart = true;
12331 switch (res) {
12332 case Service.START_STICKY_COMPATIBILITY:
12333 case Service.START_STICKY: {
12334 // We are done with the associated start arguments.
12335 r.findDeliveredStart(startId, true);
12336 // Don't stop if killed.
12337 r.stopIfKilled = false;
12338 break;
12339 }
12340 case Service.START_NOT_STICKY: {
12341 // We are done with the associated start arguments.
12342 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012343 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012344 // There is no more work, and this service
12345 // doesn't want to hang around if killed.
12346 r.stopIfKilled = true;
12347 }
12348 break;
12349 }
12350 case Service.START_REDELIVER_INTENT: {
12351 // We'll keep this item until they explicitly
12352 // call stop for it, but keep track of the fact
12353 // that it was delivered.
12354 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12355 if (si != null) {
12356 si.deliveryCount = 0;
12357 si.doneExecutingCount++;
12358 // Don't stop if killed.
12359 r.stopIfKilled = true;
12360 }
12361 break;
12362 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012363 case Service.START_TASK_REMOVED_COMPLETE: {
12364 // Special processing for onTaskRemoved(). Don't
12365 // impact normal onStartCommand() processing.
12366 r.findDeliveredStart(startId, true);
12367 break;
12368 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012369 default:
12370 throw new IllegalArgumentException(
12371 "Unknown service start result: " + res);
12372 }
12373 if (res == Service.START_STICKY_COMPATIBILITY) {
12374 r.callStart = false;
12375 }
12376 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012377 if (DEBUG_MU)
12378 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12379 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012380 final long origId = Binder.clearCallingIdentity();
12381 serviceDoneExecutingLocked(r, inStopping);
12382 Binder.restoreCallingIdentity(origId);
12383 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012384 Slog.w(TAG, "Done executing unknown service from pid "
12385 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012386 }
12387 }
12388 }
12389
12390 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012391 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12392 + ": nesting=" + r.executeNesting
12393 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012394 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012395 r.executeNesting--;
12396 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012397 if (DEBUG_SERVICE) Slog.v(TAG,
12398 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012399 r.app.executingServices.remove(r);
12400 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012401 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12402 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012403 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12404 }
12405 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012406 if (DEBUG_SERVICE) Slog.v(TAG,
12407 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012408 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012409 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012410 }
12411 updateOomAdjLocked(r.app);
12412 }
12413 }
12414
12415 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012416 String anrMessage = null;
12417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012418 synchronized(this) {
12419 if (proc.executingServices.size() == 0 || proc.thread == null) {
12420 return;
12421 }
12422 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12423 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12424 ServiceRecord timeout = null;
12425 long nextTime = 0;
12426 while (it.hasNext()) {
12427 ServiceRecord sr = it.next();
12428 if (sr.executingStart < maxTime) {
12429 timeout = sr;
12430 break;
12431 }
12432 if (sr.executingStart > nextTime) {
12433 nextTime = sr.executingStart;
12434 }
12435 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012436 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012437 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012438 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012439 } else {
12440 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12441 msg.obj = proc;
12442 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12443 }
12444 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012445
12446 if (anrMessage != null) {
12447 appNotResponding(proc, null, null, anrMessage);
12448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012449 }
12450
12451 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012452 // BACKUP AND RESTORE
12453 // =========================================================
12454
12455 // Cause the target app to be launched if necessary and its backup agent
12456 // instantiated. The backup agent will invoke backupAgentCreated() on the
12457 // activity manager to announce its creation.
12458 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012459 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012460 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12461
12462 synchronized(this) {
12463 // !!! TODO: currently no check here that we're already bound
12464 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12465 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12466 synchronized (stats) {
12467 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12468 }
12469
Dianne Hackborne7f97212011-02-24 14:40:20 -080012470 // Backup agent is now in use, its package can't be stopped.
12471 try {
12472 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012473 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012474 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012475 } catch (IllegalArgumentException e) {
12476 Slog.w(TAG, "Failed trying to unstop package "
12477 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012478 }
12479
Christopher Tate181fafa2009-05-14 11:12:14 -070012480 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012481 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12482 ? new ComponentName(app.packageName, app.backupAgentName)
12483 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012484 // startProcessLocked() returns existing proc's record if it's already running
12485 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012486 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012487 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012488 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012489 return false;
12490 }
12491
12492 r.app = proc;
12493 mBackupTarget = r;
12494 mBackupAppName = app.packageName;
12495
Christopher Tate6fa95972009-06-05 18:43:55 -070012496 // Try not to kill the process during backup
12497 updateOomAdjLocked(proc);
12498
Christopher Tate181fafa2009-05-14 11:12:14 -070012499 // If the process is already attached, schedule the creation of the backup agent now.
12500 // If it is not yet live, this will be done when it attaches to the framework.
12501 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012502 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012503 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012504 proc.thread.scheduleCreateBackupAgent(app,
12505 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012506 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012507 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012508 }
12509 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012510 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012511 }
12512 // Invariants: at this point, the target app process exists and the application
12513 // is either already running or in the process of coming up. mBackupTarget and
12514 // mBackupAppName describe the app, so that when it binds back to the AM we
12515 // know that it's scheduled for a backup-agent operation.
12516 }
12517
12518 return true;
12519 }
12520
12521 // A backup agent has just come up
12522 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012523 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012524 + " = " + agent);
12525
12526 synchronized(this) {
12527 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012528 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012529 return;
12530 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012531 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012532
Dianne Hackborn06740692010-09-22 22:46:21 -070012533 long oldIdent = Binder.clearCallingIdentity();
12534 try {
12535 IBackupManager bm = IBackupManager.Stub.asInterface(
12536 ServiceManager.getService(Context.BACKUP_SERVICE));
12537 bm.agentConnected(agentPackageName, agent);
12538 } catch (RemoteException e) {
12539 // can't happen; the backup manager service is local
12540 } catch (Exception e) {
12541 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12542 e.printStackTrace();
12543 } finally {
12544 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012545 }
12546 }
12547
12548 // done with this agent
12549 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012550 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012551 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012552 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012553 return;
12554 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012555
12556 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012557 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012558 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012559 return;
12560 }
12561
Christopher Tate181fafa2009-05-14 11:12:14 -070012562 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012563 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012564 return;
12565 }
12566
Christopher Tate6fa95972009-06-05 18:43:55 -070012567 ProcessRecord proc = mBackupTarget.app;
12568 mBackupTarget = null;
12569 mBackupAppName = null;
12570
12571 // Not backing this app up any more; reset its OOM adjustment
12572 updateOomAdjLocked(proc);
12573
Christopher Tatec7b31e32009-06-10 15:49:30 -070012574 // If the app crashed during backup, 'thread' will be null here
12575 if (proc.thread != null) {
12576 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012577 proc.thread.scheduleDestroyBackupAgent(appInfo,
12578 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012579 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012580 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012581 e.printStackTrace();
12582 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012583 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012584 }
12585 }
12586 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012587 // BROADCASTS
12588 // =========================================================
12589
Josh Bartel7f208742010-02-25 11:01:44 -060012590 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012591 List cur) {
12592 final ContentResolver resolver = mContext.getContentResolver();
12593 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12594 if (list == null) {
12595 return cur;
12596 }
12597 int N = list.size();
12598 for (int i=0; i<N; i++) {
12599 Intent intent = list.get(i);
12600 if (filter.match(resolver, intent, true, TAG) >= 0) {
12601 if (cur == null) {
12602 cur = new ArrayList<Intent>();
12603 }
12604 cur.add(intent);
12605 }
12606 }
12607 return cur;
12608 }
12609
Christopher Tatef46723b2012-01-26 14:19:24 -080012610 boolean isPendingBroadcastProcessLocked(int pid) {
12611 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12612 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012614
Christopher Tatef46723b2012-01-26 14:19:24 -080012615 void skipPendingBroadcastLocked(int pid) {
12616 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12617 for (BroadcastQueue queue : mBroadcastQueues) {
12618 queue.skipPendingBroadcastLocked(pid);
12619 }
12620 }
12621
12622 // The app just attached; send any pending broadcasts that it should receive
12623 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12624 boolean didSomething = false;
12625 for (BroadcastQueue queue : mBroadcastQueues) {
12626 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012627 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012628 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 }
12630
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012631 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012632 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012633 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012634 synchronized(this) {
12635 ProcessRecord callerApp = null;
12636 if (caller != null) {
12637 callerApp = getRecordForAppLocked(caller);
12638 if (callerApp == null) {
12639 throw new SecurityException(
12640 "Unable to find app for caller " + caller
12641 + " (pid=" + Binder.getCallingPid()
12642 + ") when registering receiver " + receiver);
12643 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012644 if (callerApp.info.uid != Process.SYSTEM_UID &&
12645 !callerApp.pkgList.contains(callerPackage)) {
12646 throw new SecurityException("Given caller package " + callerPackage
12647 + " is not running in process " + callerApp);
12648 }
12649 } else {
12650 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012651 }
12652
12653 List allSticky = null;
12654
12655 // Look for any matching sticky broadcasts...
12656 Iterator actions = filter.actionsIterator();
12657 if (actions != null) {
12658 while (actions.hasNext()) {
12659 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012660 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012661 }
12662 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012663 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012664 }
12665
12666 // The first sticky in the list is returned directly back to
12667 // the client.
12668 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12669
Joe Onorato8a9b2202010-02-26 18:56:32 -080012670 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012671 + ": " + sticky);
12672
12673 if (receiver == null) {
12674 return sticky;
12675 }
12676
12677 ReceiverList rl
12678 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12679 if (rl == null) {
12680 rl = new ReceiverList(this, callerApp,
12681 Binder.getCallingPid(),
12682 Binder.getCallingUid(), receiver);
12683 if (rl.app != null) {
12684 rl.app.receivers.add(rl);
12685 } else {
12686 try {
12687 receiver.asBinder().linkToDeath(rl, 0);
12688 } catch (RemoteException e) {
12689 return sticky;
12690 }
12691 rl.linkedToDeath = true;
12692 }
12693 mRegisteredReceivers.put(receiver.asBinder(), rl);
12694 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012695 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012696 rl.add(bf);
12697 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012698 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012699 }
12700 mReceiverResolver.addFilter(bf);
12701
12702 // Enqueue broadcasts for all existing stickies that match
12703 // this filter.
12704 if (allSticky != null) {
12705 ArrayList receivers = new ArrayList();
12706 receivers.add(bf);
12707
12708 int N = allSticky.size();
12709 for (int i=0; i<N; i++) {
12710 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012711 BroadcastQueue queue = broadcastQueueForIntent(intent);
12712 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012713 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012714 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012715 queue.enqueueParallelBroadcastLocked(r);
12716 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012717 }
12718 }
12719
12720 return sticky;
12721 }
12722 }
12723
12724 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012725 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012726
Christopher Tatef46723b2012-01-26 14:19:24 -080012727 final long origId = Binder.clearCallingIdentity();
12728 try {
12729 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012730
Christopher Tatef46723b2012-01-26 14:19:24 -080012731 synchronized(this) {
12732 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012733 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012734 if (rl != null) {
12735 if (rl.curBroadcast != null) {
12736 BroadcastRecord r = rl.curBroadcast;
12737 final boolean doNext = finishReceiverLocked(
12738 receiver.asBinder(), r.resultCode, r.resultData,
12739 r.resultExtras, r.resultAbort, true);
12740 if (doNext) {
12741 doTrim = true;
12742 r.queue.processNextBroadcast(false);
12743 }
12744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012745
Christopher Tatef46723b2012-01-26 14:19:24 -080012746 if (rl.app != null) {
12747 rl.app.receivers.remove(rl);
12748 }
12749 removeReceiverLocked(rl);
12750 if (rl.linkedToDeath) {
12751 rl.linkedToDeath = false;
12752 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012754 }
12755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012756
Christopher Tatef46723b2012-01-26 14:19:24 -080012757 // If we actually concluded any broadcasts, we might now be able
12758 // to trim the recipients' apps from our working set
12759 if (doTrim) {
12760 trimApplications();
12761 return;
12762 }
12763
12764 } finally {
12765 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012767 }
12768
12769 void removeReceiverLocked(ReceiverList rl) {
12770 mRegisteredReceivers.remove(rl.receiver.asBinder());
12771 int N = rl.size();
12772 for (int i=0; i<N; i++) {
12773 mReceiverResolver.removeFilter(rl.get(i));
12774 }
12775 }
12776
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012777 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12778 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12779 ProcessRecord r = mLruProcesses.get(i);
12780 if (r.thread != null) {
12781 try {
12782 r.thread.dispatchPackageBroadcast(cmd, packages);
12783 } catch (RemoteException ex) {
12784 }
12785 }
12786 }
12787 }
12788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012789 private final int broadcastIntentLocked(ProcessRecord callerApp,
12790 String callerPackage, Intent intent, String resolvedType,
12791 IIntentReceiver resultTo, int resultCode, String resultData,
12792 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012793 boolean ordered, boolean sticky, int callingPid, int callingUid,
12794 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012795 intent = new Intent(intent);
12796
Dianne Hackborne7f97212011-02-24 14:40:20 -080012797 // By default broadcasts do not go to stopped apps.
12798 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12799
Joe Onorato8a9b2202010-02-26 18:56:32 -080012800 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012801 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012802 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012803 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012804 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012805 }
12806
12807 // Handle special intents: if this broadcast is from the package
12808 // manager about a package being removed, we need to remove all of
12809 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012810 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012811 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012812 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12813 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012814 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012815 || uidRemoved) {
12816 if (checkComponentPermission(
12817 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012818 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012819 == PackageManager.PERMISSION_GRANTED) {
12820 if (uidRemoved) {
12821 final Bundle intentExtras = intent.getExtras();
12822 final int uid = intentExtras != null
12823 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12824 if (uid >= 0) {
12825 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12826 synchronized (bs) {
12827 bs.removeUidStatsLocked(uid);
12828 }
12829 }
12830 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012831 // If resources are unvailble just force stop all
12832 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012833 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012834 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12835 if (list != null && (list.length > 0)) {
12836 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012837 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012838 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012839 sendPackageBroadcastLocked(
12840 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012841 }
12842 } else {
12843 Uri data = intent.getData();
12844 String ssp;
12845 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12846 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12847 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012848 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12849 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012850 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012851 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012852 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12853 new String[] {ssp});
12854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012855 }
12856 }
12857 }
12858 } else {
12859 String msg = "Permission Denial: " + intent.getAction()
12860 + " broadcast from " + callerPackage + " (pid=" + callingPid
12861 + ", uid=" + callingUid + ")"
12862 + " requires "
12863 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012864 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012865 throw new SecurityException(msg);
12866 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012867
12868 // Special case for adding a package: by default turn on compatibility
12869 // mode.
12870 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012871 Uri data = intent.getData();
12872 String ssp;
12873 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12874 mCompatModePackages.handlePackageAddedLocked(ssp,
12875 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012877 }
12878
12879 /*
12880 * If this is the time zone changed action, queue up a message that will reset the timezone
12881 * of all currently running processes. This message will get queued up before the broadcast
12882 * happens.
12883 */
12884 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12885 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12886 }
12887
Robert Greenwalt03595d02010-11-02 14:08:23 -070012888 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12889 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12890 }
12891
Robert Greenwalt434203a2010-10-11 16:00:27 -070012892 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12893 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12894 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12895 }
12896
Dianne Hackborn854060af2009-07-09 18:14:31 -070012897 /*
12898 * Prevent non-system code (defined here to be non-persistent
12899 * processes) from sending protected broadcasts.
12900 */
12901 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12902 || callingUid == Process.SHELL_UID || callingUid == 0) {
12903 // Always okay.
12904 } else if (callerApp == null || !callerApp.persistent) {
12905 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012906 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012907 intent.getAction())) {
12908 String msg = "Permission Denial: not allowed to send broadcast "
12909 + intent.getAction() + " from pid="
12910 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012911 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012912 throw new SecurityException(msg);
12913 }
12914 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012915 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012916 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012917 }
12918 }
12919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012920 // Add to the sticky list if requested.
12921 if (sticky) {
12922 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12923 callingPid, callingUid)
12924 != PackageManager.PERMISSION_GRANTED) {
12925 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12926 + callingPid + ", uid=" + callingUid
12927 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012928 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012929 throw new SecurityException(msg);
12930 }
12931 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012932 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012933 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012934 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012935 }
12936 if (intent.getComponent() != null) {
12937 throw new SecurityException(
12938 "Sticky broadcasts can't target a specific component");
12939 }
12940 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12941 if (list == null) {
12942 list = new ArrayList<Intent>();
12943 mStickyBroadcasts.put(intent.getAction(), list);
12944 }
12945 int N = list.size();
12946 int i;
12947 for (i=0; i<N; i++) {
12948 if (intent.filterEquals(list.get(i))) {
12949 // This sticky already exists, replace it.
12950 list.set(i, new Intent(intent));
12951 break;
12952 }
12953 }
12954 if (i >= N) {
12955 list.add(new Intent(intent));
12956 }
12957 }
12958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959 // Figure out who all will receive this broadcast.
12960 List receivers = null;
12961 List<BroadcastFilter> registeredReceivers = null;
12962 try {
12963 if (intent.getComponent() != null) {
12964 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012965 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012966 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012967 if (ai != null) {
12968 receivers = new ArrayList();
12969 ResolveInfo ri = new ResolveInfo();
Amith Yamasania4a54e22012-04-16 15:44:19 -070012970 if (isSingleton(ai.processName, ai.applicationInfo)) {
12971 ri.activityInfo = getActivityInfoForUser(ai, 0);
12972 } else {
12973 ri.activityInfo = getActivityInfoForUser(ai, userId);
12974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012975 receivers.add(ri);
12976 }
12977 } else {
12978 // Need to resolve the intent to interested receivers...
12979 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12980 == 0) {
12981 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012982 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012983 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012984 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012985 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12986 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012987 }
12988 } catch (RemoteException ex) {
12989 // pm is in same process, this will never happen.
12990 }
12991
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012992 final boolean replacePending =
12993 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12994
Joe Onorato8a9b2202010-02-26 18:56:32 -080012995 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012996 + " replacePending=" + replacePending);
12997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012998 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12999 if (!ordered && NR > 0) {
13000 // If we are not serializing this broadcast, then send the
13001 // registered receivers separately so they don't wait for the
13002 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080013003 final BroadcastQueue queue = broadcastQueueForIntent(intent);
13004 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013005 callerPackage, callingPid, callingUid, requiredPermission,
13006 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013007 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013008 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080013009 TAG, "Enqueueing parallel broadcast " + r);
13010 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013011 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013012 queue.enqueueParallelBroadcastLocked(r);
13013 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013015 registeredReceivers = null;
13016 NR = 0;
13017 }
13018
13019 // Merge into one list.
13020 int ir = 0;
13021 if (receivers != null) {
13022 // A special case for PACKAGE_ADDED: do not allow the package
13023 // being added to see this broadcast. This prevents them from
13024 // using this as a back door to get run as soon as they are
13025 // installed. Maybe in the future we want to have a special install
13026 // broadcast or such for apps, but we'd like to deliberately make
13027 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013028 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013029 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
13030 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
13031 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013032 Uri data = intent.getData();
13033 if (data != null) {
13034 String pkgName = data.getSchemeSpecificPart();
13035 if (pkgName != null) {
13036 skipPackages = new String[] { pkgName };
13037 }
13038 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013039 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013040 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070013041 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013042 if (skipPackages != null && (skipPackages.length > 0)) {
13043 for (String skipPackage : skipPackages) {
13044 if (skipPackage != null) {
13045 int NT = receivers.size();
13046 for (int it=0; it<NT; it++) {
13047 ResolveInfo curt = (ResolveInfo)receivers.get(it);
13048 if (curt.activityInfo.packageName.equals(skipPackage)) {
13049 receivers.remove(it);
13050 it--;
13051 NT--;
13052 }
13053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013054 }
13055 }
13056 }
13057
13058 int NT = receivers != null ? receivers.size() : 0;
13059 int it = 0;
13060 ResolveInfo curt = null;
13061 BroadcastFilter curr = null;
13062 while (it < NT && ir < NR) {
13063 if (curt == null) {
13064 curt = (ResolveInfo)receivers.get(it);
13065 }
13066 if (curr == null) {
13067 curr = registeredReceivers.get(ir);
13068 }
13069 if (curr.getPriority() >= curt.priority) {
13070 // Insert this broadcast record into the final list.
13071 receivers.add(it, curr);
13072 ir++;
13073 curr = null;
13074 it++;
13075 NT++;
13076 } else {
13077 // Skip to the next ResolveInfo in the final list.
13078 it++;
13079 curt = null;
13080 }
13081 }
13082 }
13083 while (ir < NR) {
13084 if (receivers == null) {
13085 receivers = new ArrayList();
13086 }
13087 receivers.add(registeredReceivers.get(ir));
13088 ir++;
13089 }
13090
13091 if ((receivers != null && receivers.size() > 0)
13092 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013093 BroadcastQueue queue = broadcastQueueForIntent(intent);
13094 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013095 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013096 receivers, resultTo, resultCode, resultData, map, ordered,
13097 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013098 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013099 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080013100 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013101 if (DEBUG_BROADCAST) {
13102 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013103 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013104 }
Christopher Tatef46723b2012-01-26 14:19:24 -080013105 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013106 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013107 queue.enqueueOrderedBroadcastLocked(r);
13108 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013110 }
13111
Dianne Hackborna4972e92012-03-14 10:38:05 -070013112 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013113 }
13114
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013115 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013116 // Refuse possible leaked file descriptors
13117 if (intent != null && intent.hasFileDescriptors() == true) {
13118 throw new IllegalArgumentException("File descriptors passed in Intent");
13119 }
13120
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013121 int flags = intent.getFlags();
13122
13123 if (!mProcessesReady) {
13124 // if the caller really truly claims to know what they're doing, go
13125 // ahead and allow the broadcast without launching any receivers
13126 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
13127 intent = new Intent(intent);
13128 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
13129 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
13130 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
13131 + " before boot completion");
13132 throw new IllegalStateException("Cannot broadcast before boot completed");
13133 }
13134 }
13135
13136 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
13137 throw new IllegalArgumentException(
13138 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
13139 }
13140
13141 return intent;
13142 }
13143
13144 public final int broadcastIntent(IApplicationThread caller,
13145 Intent intent, String resolvedType, IIntentReceiver resultTo,
13146 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013147 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013148 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013149 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013150 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070013151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013152 final ProcessRecord callerApp = getRecordForAppLocked(caller);
13153 final int callingPid = Binder.getCallingPid();
13154 final int callingUid = Binder.getCallingUid();
13155 final long origId = Binder.clearCallingIdentity();
13156 int res = broadcastIntentLocked(callerApp,
13157 callerApp != null ? callerApp.info.packageName : null,
13158 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070013159 resultCode, resultData, map, requiredPermission, serialized, sticky,
13160 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013161 Binder.restoreCallingIdentity(origId);
13162 return res;
13163 }
13164 }
13165
13166 int broadcastIntentInPackage(String packageName, int uid,
13167 Intent intent, String resolvedType, IIntentReceiver resultTo,
13168 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013169 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013170 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013171 intent = verifyBroadcastLocked(intent);
13172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013173 final long origId = Binder.clearCallingIdentity();
13174 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
13175 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013176 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013177 Binder.restoreCallingIdentity(origId);
13178 return res;
13179 }
13180 }
13181
Amith Yamasani742a6712011-05-04 14:49:28 -070013182 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
13183 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013184 // Refuse possible leaked file descriptors
13185 if (intent != null && intent.hasFileDescriptors() == true) {
13186 throw new IllegalArgumentException("File descriptors passed in Intent");
13187 }
13188
13189 synchronized(this) {
13190 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13191 != PackageManager.PERMISSION_GRANTED) {
13192 String msg = "Permission Denial: unbroadcastIntent() from pid="
13193 + Binder.getCallingPid()
13194 + ", uid=" + Binder.getCallingUid()
13195 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013196 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013197 throw new SecurityException(msg);
13198 }
13199 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13200 if (list != null) {
13201 int N = list.size();
13202 int i;
13203 for (i=0; i<N; i++) {
13204 if (intent.filterEquals(list.get(i))) {
13205 list.remove(i);
13206 break;
13207 }
13208 }
13209 }
13210 }
13211 }
13212
13213 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13214 String resultData, Bundle resultExtras, boolean resultAbort,
13215 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013216 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13217 if (r == null) {
13218 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013219 return false;
13220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013221
Christopher Tatef46723b2012-01-26 14:19:24 -080013222 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13223 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013224 }
13225
13226 public void finishReceiver(IBinder who, int resultCode, String resultData,
13227 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013228 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013229
13230 // Refuse possible leaked file descriptors
13231 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13232 throw new IllegalArgumentException("File descriptors passed in Bundle");
13233 }
13234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013235 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013236 try {
13237 boolean doNext = false;
13238 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013239
Christopher Tatef46723b2012-01-26 14:19:24 -080013240 synchronized(this) {
13241 r = broadcastRecordForReceiverLocked(who);
13242 if (r != null) {
13243 doNext = r.queue.finishReceiverLocked(r, resultCode,
13244 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013246 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013247
Christopher Tatef46723b2012-01-26 14:19:24 -080013248 if (doNext) {
13249 r.queue.processNextBroadcast(false);
13250 }
13251 trimApplications();
13252 } finally {
13253 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013257 // =========================================================
13258 // INSTRUMENTATION
13259 // =========================================================
13260
13261 public boolean startInstrumentation(ComponentName className,
13262 String profileFile, int flags, Bundle arguments,
13263 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013264 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013265 // Refuse possible leaked file descriptors
13266 if (arguments != null && arguments.hasFileDescriptors()) {
13267 throw new IllegalArgumentException("File descriptors passed in Bundle");
13268 }
13269
13270 synchronized(this) {
13271 InstrumentationInfo ii = null;
13272 ApplicationInfo ai = null;
13273 try {
13274 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013275 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013276 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070013277 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013278 } catch (PackageManager.NameNotFoundException e) {
13279 }
13280 if (ii == null) {
13281 reportStartInstrumentationFailure(watcher, className,
13282 "Unable to find instrumentation info for: " + className);
13283 return false;
13284 }
13285 if (ai == null) {
13286 reportStartInstrumentationFailure(watcher, className,
13287 "Unable to find instrumentation target package: " + ii.targetPackage);
13288 return false;
13289 }
13290
13291 int match = mContext.getPackageManager().checkSignatures(
13292 ii.targetPackage, ii.packageName);
13293 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13294 String msg = "Permission Denial: starting instrumentation "
13295 + className + " from pid="
13296 + Binder.getCallingPid()
13297 + ", uid=" + Binder.getCallingPid()
13298 + " not allowed because package " + ii.packageName
13299 + " does not have a signature matching the target "
13300 + ii.targetPackage;
13301 reportStartInstrumentationFailure(watcher, className, msg);
13302 throw new SecurityException(msg);
13303 }
13304
Amith Yamasani483f3b02012-03-13 16:08:00 -070013305 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013306 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013307 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013308 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013309 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013310 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013311 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013312 app.instrumentationProfileFile = profileFile;
13313 app.instrumentationArguments = arguments;
13314 app.instrumentationWatcher = watcher;
13315 app.instrumentationResultClass = className;
13316 Binder.restoreCallingIdentity(origId);
13317 }
13318
13319 return true;
13320 }
13321
13322 /**
13323 * Report errors that occur while attempting to start Instrumentation. Always writes the
13324 * error to the logs, but if somebody is watching, send the report there too. This enables
13325 * the "am" command to report errors with more information.
13326 *
13327 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13328 * @param cn The component name of the instrumentation.
13329 * @param report The error report.
13330 */
13331 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13332 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013333 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013334 try {
13335 if (watcher != null) {
13336 Bundle results = new Bundle();
13337 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13338 results.putString("Error", report);
13339 watcher.instrumentationStatus(cn, -1, results);
13340 }
13341 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013342 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013343 }
13344 }
13345
13346 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13347 if (app.instrumentationWatcher != null) {
13348 try {
13349 // NOTE: IInstrumentationWatcher *must* be oneway here
13350 app.instrumentationWatcher.instrumentationFinished(
13351 app.instrumentationClass,
13352 resultCode,
13353 results);
13354 } catch (RemoteException e) {
13355 }
13356 }
13357 app.instrumentationWatcher = null;
13358 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013359 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013360 app.instrumentationProfileFile = null;
13361 app.instrumentationArguments = null;
13362
Amith Yamasani483f3b02012-03-13 16:08:00 -070013363 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013364 }
13365
13366 public void finishInstrumentation(IApplicationThread target,
13367 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013368 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013369 // Refuse possible leaked file descriptors
13370 if (results != null && results.hasFileDescriptors()) {
13371 throw new IllegalArgumentException("File descriptors passed in Intent");
13372 }
13373
13374 synchronized(this) {
13375 ProcessRecord app = getRecordForAppLocked(target);
13376 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013377 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013378 return;
13379 }
13380 final long origId = Binder.clearCallingIdentity();
13381 finishInstrumentationLocked(app, resultCode, results);
13382 Binder.restoreCallingIdentity(origId);
13383 }
13384 }
13385
13386 // =========================================================
13387 // CONFIGURATION
13388 // =========================================================
13389
13390 public ConfigurationInfo getDeviceConfigurationInfo() {
13391 ConfigurationInfo config = new ConfigurationInfo();
13392 synchronized (this) {
13393 config.reqTouchScreen = mConfiguration.touchscreen;
13394 config.reqKeyboardType = mConfiguration.keyboard;
13395 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013396 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13397 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013398 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13399 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013400 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13401 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013402 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13403 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013404 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013405 }
13406 return config;
13407 }
13408
13409 public Configuration getConfiguration() {
13410 Configuration ci;
13411 synchronized(this) {
13412 ci = new Configuration(mConfiguration);
13413 }
13414 return ci;
13415 }
13416
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013417 public void updatePersistentConfiguration(Configuration values) {
13418 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13419 "updateConfiguration()");
13420 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13421 "updateConfiguration()");
13422 if (values == null) {
13423 throw new NullPointerException("Configuration must not be null");
13424 }
13425
13426 synchronized(this) {
13427 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013428 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013429 Binder.restoreCallingIdentity(origId);
13430 }
13431 }
13432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013433 public void updateConfiguration(Configuration values) {
13434 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13435 "updateConfiguration()");
13436
13437 synchronized(this) {
13438 if (values == null && mWindowManager != null) {
13439 // sentinel: fetch the current configuration from the window manager
13440 values = mWindowManager.computeNewConfiguration();
13441 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013442
13443 if (mWindowManager != null) {
13444 mProcessList.applyDisplaySize(mWindowManager);
13445 }
13446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013447 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013448 if (values != null) {
13449 Settings.System.clearConfiguration(values);
13450 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013451 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013452 Binder.restoreCallingIdentity(origId);
13453 }
13454 }
13455
13456 /**
13457 * Do either or both things: (1) change the current configuration, and (2)
13458 * make sure the given activity is running with the (now) current
13459 * configuration. Returns true if the activity has been left running, or
13460 * false if <var>starting</var> is being destroyed to match the new
13461 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013462 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013463 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013464 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013465 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013466 // do nothing if we are headless
13467 if (mHeadless) return true;
13468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013469 int changes = 0;
13470
13471 boolean kept = true;
13472
13473 if (values != null) {
13474 Configuration newConfig = new Configuration(mConfiguration);
13475 changes = newConfig.updateFrom(values);
13476 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013477 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013478 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013479 }
13480
Doug Zongker2bec3d42009-12-04 12:52:44 -080013481 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013482
Dianne Hackborn813075a62011-11-14 17:45:19 -080013483 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013484 saveLocaleLocked(values.locale,
13485 !values.locale.equals(mConfiguration.locale),
13486 values.userSetLocale);
13487 }
13488
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013489 mConfigurationSeq++;
13490 if (mConfigurationSeq <= 0) {
13491 mConfigurationSeq = 1;
13492 }
13493 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013494 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013495 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013496
13497 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013498
13499 // TODO: If our config changes, should we auto dismiss any currently
13500 // showing dialogs?
13501 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013502
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013503 AttributeCache ac = AttributeCache.instance();
13504 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013505 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013507
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013508 // Make sure all resources in our process are updated
13509 // right now, so that anyone who is going to retrieve
13510 // resource values after we return will be sure to get
13511 // the new ones. This is especially important during
13512 // boot, where the first config change needs to guarantee
13513 // all resources have that config before following boot
13514 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013515 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013516
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013517 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013518 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013519 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013520 mHandler.sendMessage(msg);
13521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013522
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013523 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13524 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013525 try {
13526 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013527 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013528 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013529 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013530 }
13531 } catch (Exception e) {
13532 }
13533 }
13534 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013535 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13536 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013537 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013538 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013539 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13540 broadcastIntentLocked(null, null,
13541 new Intent(Intent.ACTION_LOCALE_CHANGED),
13542 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013543 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013545 }
13546 }
13547
13548 if (changes != 0 && starting == null) {
13549 // If the configuration changed, and the caller is not already
13550 // in the process of starting an activity, then find the top
13551 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013552 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013553 }
13554
13555 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013556 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013557 // And we need to make sure at this point that all other activities
13558 // are made visible with the correct configuration.
13559 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013560 }
13561
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013562 if (values != null && mWindowManager != null) {
13563 mWindowManager.setNewConfiguration(mConfiguration);
13564 }
13565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013566 return kept;
13567 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013568
13569 /**
13570 * Decide based on the configuration whether we should shouw the ANR,
13571 * crash, etc dialogs. The idea is that if there is no affordnace to
13572 * press the on-screen buttons, we shouldn't show the dialog.
13573 *
13574 * A thought: SystemUI might also want to get told about this, the Power
13575 * dialog / global actions also might want different behaviors.
13576 */
13577 private static final boolean shouldShowDialogs(Configuration config) {
13578 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13579 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013581
13582 /**
13583 * Save the locale. You must be inside a synchronized (this) block.
13584 */
13585 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13586 if(isDiff) {
13587 SystemProperties.set("user.language", l.getLanguage());
13588 SystemProperties.set("user.region", l.getCountry());
13589 }
13590
13591 if(isPersist) {
13592 SystemProperties.set("persist.sys.language", l.getLanguage());
13593 SystemProperties.set("persist.sys.country", l.getCountry());
13594 SystemProperties.set("persist.sys.localevar", l.getVariant());
13595 }
13596 }
13597
Adam Powelldd8fab22012-03-22 17:47:27 -070013598 @Override
13599 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13600 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013601 return srec != null && srec.task.affinity != null &&
13602 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070013603 }
13604
13605 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13606 Intent resultData) {
13607 ComponentName dest = destIntent.getComponent();
13608
13609 synchronized (this) {
13610 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013611 if (srec == null) {
13612 return false;
13613 }
Adam Powelldd8fab22012-03-22 17:47:27 -070013614 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13615 final int start = history.indexOf(srec);
13616 if (start < 0) {
13617 // Current activity is not in history stack; do nothing.
13618 return false;
13619 }
13620 int finishTo = start - 1;
13621 ActivityRecord parent = null;
13622 boolean foundParentInTask = false;
13623 if (dest != null) {
13624 TaskRecord tr = srec.task;
13625 for (int i = start - 1; i >= 0; i--) {
13626 ActivityRecord r = history.get(i);
13627 if (tr != r.task) {
13628 // Couldn't find parent in the same task; stop at the one above this.
13629 // (Root of current task; in-app "home" behavior)
13630 // Always at least finish the current activity.
13631 finishTo = Math.min(start - 1, i + 1);
13632 parent = history.get(finishTo);
13633 break;
13634 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13635 r.info.name.equals(dest.getClassName())) {
13636 finishTo = i;
13637 parent = r;
13638 foundParentInTask = true;
13639 break;
13640 }
13641 }
13642 }
13643
13644 if (mController != null) {
13645 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13646 if (next != null) {
13647 // ask watcher if this is allowed
13648 boolean resumeOK = true;
13649 try {
13650 resumeOK = mController.activityResuming(next.packageName);
13651 } catch (RemoteException e) {
13652 mController = null;
13653 }
13654
13655 if (!resumeOK) {
13656 return false;
13657 }
13658 }
13659 }
13660 final long origId = Binder.clearCallingIdentity();
13661 for (int i = start; i > finishTo; i--) {
13662 ActivityRecord r = history.get(i);
13663 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13664 "navigate-up");
13665 // Only return the supplied result for the first activity finished
13666 resultCode = Activity.RESULT_CANCELED;
13667 resultData = null;
13668 }
13669
13670 if (parent != null && foundParentInTask) {
13671 final int parentLaunchMode = parent.info.launchMode;
13672 final int destIntentFlags = destIntent.getFlags();
13673 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13674 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13675 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13676 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070013677 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070013678 } else {
13679 try {
13680 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13681 destIntent.getComponent(), 0, UserId.getCallingUserId());
13682 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13683 null, aInfo, parent.appToken, null,
13684 0, -1, parent.launchedFromUid, 0, null, true, null);
13685 foundParentInTask = res == ActivityManager.START_SUCCESS;
13686 } catch (RemoteException e) {
13687 foundParentInTask = false;
13688 }
13689 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13690 resultData, "navigate-up");
13691 }
13692 }
13693 Binder.restoreCallingIdentity(origId);
13694 return foundParentInTask;
13695 }
13696 }
13697
Dianne Hackborn5320eb82012-05-18 12:05:04 -070013698 public int getLaunchedFromUid(IBinder activityToken) {
13699 ActivityRecord srec = ActivityRecord.forToken(activityToken);
13700 if (srec == null) {
13701 return -1;
13702 }
13703 return srec.launchedFromUid;
13704 }
13705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013706 // =========================================================
13707 // LIFETIME MANAGEMENT
13708 // =========================================================
13709
Christopher Tatef46723b2012-01-26 14:19:24 -080013710 // Returns which broadcast queue the app is the current [or imminent] receiver
13711 // on, or 'null' if the app is not an active broadcast recipient.
13712 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13713 BroadcastRecord r = app.curReceiver;
13714 if (r != null) {
13715 return r.queue;
13716 }
13717
13718 // It's not the current receiver, but it might be starting up to become one
13719 synchronized (this) {
13720 for (BroadcastQueue queue : mBroadcastQueues) {
13721 r = queue.mPendingBroadcast;
13722 if (r != null && r.curApp == app) {
13723 // found it; report which queue it's in
13724 return queue;
13725 }
13726 }
13727 }
13728
13729 return null;
13730 }
13731
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013732 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013733 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013734 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013735 // This adjustment has already been computed. If we are calling
13736 // from the top, we may have already computed our adjustment with
13737 // an earlier hidden adjustment that isn't really for us... if
13738 // so, use the new hidden adjustment.
13739 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013740 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013741 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013742 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013743 }
13744
13745 if (app.thread == null) {
13746 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013747 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013748 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013749 }
13750
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013751 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13752 app.adjSource = null;
13753 app.adjTarget = null;
13754 app.empty = false;
13755 app.hidden = false;
13756
13757 final int activitiesSize = app.activities.size();
13758
Dianne Hackborn7d608422011-08-07 16:24:18 -070013759 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013760 // The max adjustment doesn't allow this app to be anything
13761 // below foreground, so it is not worth doing work for it.
13762 app.adjType = "fixed";
13763 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013764 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013765 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013766 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013767 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013768 // System process can do UI, and when they do we want to have
13769 // them trim their memory after the user leaves the UI. To
13770 // facilitate this, here we need to determine whether or not it
13771 // is currently showing UI.
13772 app.systemNoUi = true;
13773 if (app == TOP_APP) {
13774 app.systemNoUi = false;
13775 } else if (activitiesSize > 0) {
13776 for (int j = 0; j < activitiesSize; j++) {
13777 final ActivityRecord r = app.activities.get(j);
13778 if (r.visible) {
13779 app.systemNoUi = false;
13780 break;
13781 }
13782 }
13783 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013784 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013785 }
13786
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013787 app.keeping = false;
13788 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013789
The Android Open Source Project4df24232009-03-05 14:34:35 -080013790 // Determine the importance of the process, starting with most
13791 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013792 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013793 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013794 boolean foregroundActivities = false;
13795 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080013796 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013797 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013798 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013799 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013800 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013801 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013802 foregroundActivities = true;
13803 interesting = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013804 } else if (app.instrumentationClass != null) {
13805 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013806 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013807 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013808 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013809 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080013810 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013811 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013812 // counts as being in the foreground for OOM killer purposes.
13813 // It's placed in a sched group based on the nature of the
13814 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013815 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013816 schedGroup = (queue == mFgBroadcastQueue)
13817 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013818 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013819 } else if (app.executingServices.size() > 0) {
13820 // An app that is currently executing a service callback also
13821 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013822 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013823 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013824 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013825 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013826 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013827 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013828 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013829 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013830 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013831 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013832 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013833 // A very not-needed process. If this is lower in the lru list,
13834 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013835 adj = hiddenAdj;
13836 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013837 app.hidden = true;
13838 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013839 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013840 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013841
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013842 boolean hasStoppingActivities = false;
13843
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013844 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013845 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013846 for (int j = 0; j < activitiesSize; j++) {
13847 final ActivityRecord r = app.activities.get(j);
13848 if (r.visible) {
13849 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013850 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13851 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013852 app.adjType = "visible";
13853 }
13854 schedGroup = Process.THREAD_GROUP_DEFAULT;
13855 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013856 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013857 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013858 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013859 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13860 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013861 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013862 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013863 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013864 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013865 } else if (r.state == ActivityState.STOPPING) {
13866 // We will apply the actual adjustment later, because
13867 // we want to allow this process to immediately go through
13868 // any memory trimming that is in effect.
13869 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013870 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013871 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013872 }
13873 }
13874 }
13875
Dianne Hackborn7d608422011-08-07 16:24:18 -070013876 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013877 if (app.foregroundServices) {
13878 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013879 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013880 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013881 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013882 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013883 } else if (app.forcingToForeground != null) {
13884 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013885 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013886 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013887 app.adjType = "force-foreground";
13888 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013889 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013890 }
13891 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013892
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013893 if (app.foregroundServices) {
13894 interesting = true;
13895 }
13896
Dianne Hackborn7d608422011-08-07 16:24:18 -070013897 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013898 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013899 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013900 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013901 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013902 app.adjType = "heavy";
13903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013904
Dianne Hackborn7d608422011-08-07 16:24:18 -070013905 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013906 // This process is hosting what we currently consider to be the
13907 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013908 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013909 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013910 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013911 app.adjType = "home";
13912 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013913
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013914 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13915 && app.activities.size() > 0) {
13916 // This was the previous process that showed UI to the user.
13917 // We want to try to keep it around more aggressively, to give
13918 // a good experience around switching between two apps.
13919 adj = ProcessList.PREVIOUS_APP_ADJ;
13920 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13921 app.hidden = false;
13922 app.adjType = "previous";
13923 }
13924
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013925 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13926 + " reason=" + app.adjType);
13927
The Android Open Source Project4df24232009-03-05 14:34:35 -080013928 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013929 // there are applications dependent on our services or providers, but
13930 // this gives us a baseline and makes sure we don't get into an
13931 // infinite recursion.
13932 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013933 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013934
Christopher Tate6fa95972009-06-05 18:43:55 -070013935 if (mBackupTarget != null && app == mBackupTarget.app) {
13936 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013937 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013938 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013939 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013940 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013941 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013942 }
13943 }
13944
Dianne Hackborn7d608422011-08-07 16:24:18 -070013945 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013946 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013947 final long now = SystemClock.uptimeMillis();
13948 // This process is more important if the top activity is
13949 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013950 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013951 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013952 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013953 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013954 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013955 // If this process has shown some UI, let it immediately
13956 // go to the LRU list because it may be pretty heavy with
13957 // UI stuff. We'll tag it with a label just to help
13958 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013959 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013960 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013961 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013962 } else {
13963 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13964 // This service has seen some activity within
13965 // recent memory, so we will keep its process ahead
13966 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013967 if (adj > ProcessList.SERVICE_ADJ) {
13968 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013969 app.adjType = "started-services";
13970 app.hidden = false;
13971 }
13972 }
13973 // If we have let the service slide into the background
13974 // state, still have some text describing what it is doing
13975 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013976 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013977 app.adjType = "started-bg-services";
13978 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013979 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013980 // Don't kill this process because it is doing work; it
13981 // has said it is doing work.
13982 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013983 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013984 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013985 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013986 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013987 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013988 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013989 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013990 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013991 // XXX should compute this based on the max of
13992 // all connected clients.
13993 ConnectionRecord cr = clist.get(i);
13994 if (cr.binding.client == app) {
13995 // Binding to ourself is not interesting.
13996 continue;
13997 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013998 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013999 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014000 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014001 int myHiddenAdj = hiddenAdj;
14002 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014003 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014004 myHiddenAdj = client.hiddenAdj;
14005 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014006 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014007 }
14008 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014009 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014010 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014011 String adjType = null;
14012 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
14013 // Not doing bind OOM management, so treat
14014 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014015 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014016 // If this process has shown some UI, let it immediately
14017 // go to the LRU list because it may be pretty heavy with
14018 // UI stuff. We'll tag it with a label just to help
14019 // debug and understand what is going on.
14020 if (adj > clientAdj) {
14021 adjType = "bound-bg-ui-services";
14022 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014023 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014024 clientAdj = adj;
14025 } else {
14026 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
14027 // This service has not seen activity within
14028 // recent memory, so allow it to drop to the
14029 // LRU list if there is no other reason to keep
14030 // it around. We'll also tag it with a label just
14031 // to help debug and undertand what is going on.
14032 if (adj > clientAdj) {
14033 adjType = "bound-bg-services";
14034 }
14035 clientAdj = adj;
14036 }
14037 }
14038 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014039 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014040 // If this process has recently shown UI, and
14041 // the process that is binding to it is less
14042 // important than being visible, then we don't
14043 // care about the binding as much as we care
14044 // about letting this process get into the LRU
14045 // list to be killed and restarted if needed for
14046 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014047 if (app.hasShownUi && app != mHomeProcess
14048 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014049 adjType = "bound-bg-ui-services";
14050 } else {
14051 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
14052 |Context.BIND_IMPORTANT)) != 0) {
14053 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014054 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
14055 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
14056 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14057 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14058 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014059 adj = clientAdj;
14060 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014061 app.pendingUiClean = true;
14062 if (adj > ProcessList.VISIBLE_APP_ADJ) {
14063 adj = ProcessList.VISIBLE_APP_ADJ;
14064 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014065 }
14066 if (!client.hidden) {
14067 app.hidden = false;
14068 }
14069 if (client.keeping) {
14070 app.keeping = true;
14071 }
14072 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014073 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014074 }
14075 if (adjType != null) {
14076 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014077 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14078 .REASON_SERVICE_IN_USE;
14079 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014080 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014081 app.adjTarget = s.name;
14082 }
14083 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14084 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14085 schedGroup = Process.THREAD_GROUP_DEFAULT;
14086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014087 }
14088 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014089 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
14090 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014091 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014092 (a.visible || a.state == ActivityState.RESUMED
14093 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014094 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014095 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14096 schedGroup = Process.THREAD_GROUP_DEFAULT;
14097 }
14098 app.hidden = false;
14099 app.adjType = "service";
14100 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14101 .REASON_SERVICE_IN_USE;
14102 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014103 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014104 app.adjTarget = s.name;
14105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014106 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014107 }
14108 }
14109 }
14110 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014111
Dianne Hackborn287952c2010-09-22 22:34:31 -070014112 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014113 // would like to avoid killing it unless it would prevent the current
14114 // application from running. By default we put the process in
14115 // with the rest of the background processes; as we scan through
14116 // its services we may bump it up from there.
14117 if (adj > hiddenAdj) {
14118 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014119 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014120 app.adjType = "bg-services";
14121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014122 }
14123
Dianne Hackborn7d608422011-08-07 16:24:18 -070014124 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014125 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014126 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014127 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014128 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014129 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014130 for (int i = cpr.connections.size()-1;
14131 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
14132 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
14133 i--) {
14134 ContentProviderConnection conn = cpr.connections.get(i);
14135 ProcessRecord client = conn.client;
14136 if (client == app) {
14137 // Being our own client is not interesting.
14138 continue;
14139 }
14140 int myHiddenAdj = hiddenAdj;
14141 if (myHiddenAdj > client.hiddenAdj) {
14142 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
14143 myHiddenAdj = client.hiddenAdj;
14144 } else {
14145 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070014146 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014147 }
14148 int clientAdj = computeOomAdjLocked(
14149 client, myHiddenAdj, TOP_APP, true, doingAll);
14150 if (adj > clientAdj) {
14151 if (app.hasShownUi && app != mHomeProcess
14152 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14153 app.adjType = "bg-ui-provider";
14154 } else {
14155 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
14156 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
14157 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014158 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014159 if (!client.hidden) {
14160 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014161 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014162 if (client.keeping) {
14163 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014164 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014165 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14166 .REASON_PROVIDER_IN_USE;
14167 app.adjSource = client;
14168 app.adjSourceOom = clientAdj;
14169 app.adjTarget = cpr.name;
14170 }
14171 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14172 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014173 }
14174 }
14175 // If the provider has external (non-framework) process
14176 // dependencies, ensure that its adjustment is at least
14177 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080014178 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014179 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
14180 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014181 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014182 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014183 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014184 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014185 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014186 }
14187 }
14188 }
14189 }
14190
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014191 if (adj == ProcessList.SERVICE_ADJ) {
14192 if (doingAll) {
14193 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
14194 mNewNumServiceProcs++;
14195 }
14196 if (app.serviceb) {
14197 adj = ProcessList.SERVICE_B_ADJ;
14198 }
14199 } else {
14200 app.serviceb = false;
14201 }
14202
14203 app.nonStoppingAdj = adj;
14204
14205 if (hasStoppingActivities) {
14206 // Only upgrade adjustment.
14207 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14208 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14209 app.adjType = "stopping";
14210 }
14211 }
14212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014213 app.curRawAdj = adj;
14214
Joe Onorato8a9b2202010-02-26 18:56:32 -080014215 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014216 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14217 if (adj > app.maxAdj) {
14218 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014219 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014220 schedGroup = Process.THREAD_GROUP_DEFAULT;
14221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014222 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014223 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014224 app.keeping = true;
14225 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014226
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014227 if (app.hasAboveClient) {
14228 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14229 // then we need to drop its adjustment to be lower than the service's
14230 // in order to honor the request. We want to drop it by one adjustment
14231 // level... but there is special meaning applied to various levels so
14232 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014233 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014234 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014235 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14236 adj = ProcessList.VISIBLE_APP_ADJ;
14237 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14238 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14239 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14240 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014241 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014242 adj++;
14243 }
14244 }
14245
Dianne Hackborna93c2c12012-05-31 15:29:36 -070014246 int importance = app.memImportance;
14247 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
14248 app.curAdj = adj;
14249 app.curSchedGroup = schedGroup;
14250 if (!interesting) {
14251 // For this reporting, if there is not something explicitly
14252 // interesting in this process then we will push it to the
14253 // background importance.
14254 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
14255 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
14256 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
14257 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
14258 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
14259 } else if (adj >= ProcessList.HOME_APP_ADJ) {
14260 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
14261 } else if (adj >= ProcessList.SERVICE_ADJ) {
14262 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
14263 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
14264 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
14265 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
14266 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
14267 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
14268 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
14269 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
14270 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
14271 } else {
14272 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
14273 }
14274 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014275
Dianne Hackborna93c2c12012-05-31 15:29:36 -070014276 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
14277 if (foregroundActivities != app.foregroundActivities) {
14278 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
14279 }
14280 if (changes != 0) {
14281 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
14282 app.memImportance = importance;
14283 app.foregroundActivities = foregroundActivities;
14284 int i = mPendingProcessChanges.size()-1;
14285 ProcessChangeItem item = null;
14286 while (i >= 0) {
14287 item = mPendingProcessChanges.get(i);
14288 if (item.pid == app.pid) {
14289 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
14290 break;
14291 }
14292 i--;
14293 }
14294 if (i < 0) {
14295 // No existing item in pending changes; need a new one.
14296 final int NA = mAvailProcessChanges.size();
14297 if (NA > 0) {
14298 item = mAvailProcessChanges.remove(NA-1);
14299 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
14300 } else {
14301 item = new ProcessChangeItem();
14302 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
14303 }
14304 item.changes = 0;
14305 item.pid = app.pid;
14306 item.uid = app.info.uid;
14307 if (mPendingProcessChanges.size() == 0) {
14308 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
14309 "*** Enqueueing dispatch processes changed!");
14310 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
14311 }
14312 mPendingProcessChanges.add(item);
14313 }
14314 item.changes |= changes;
14315 item.importance = importance;
14316 item.foregroundActivities = foregroundActivities;
14317 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
14318 + Integer.toHexString(System.identityHashCode(item))
14319 + " " + app.toShortString() + ": changes=" + item.changes
14320 + " importance=" + item.importance
14321 + " foreground=" + item.foregroundActivities
14322 + " type=" + app.adjType + " source=" + app.adjSource
14323 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014324 }
14325
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014326 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014327 }
14328
14329 /**
14330 * Ask a given process to GC right now.
14331 */
14332 final void performAppGcLocked(ProcessRecord app) {
14333 try {
14334 app.lastRequestedGc = SystemClock.uptimeMillis();
14335 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014336 if (app.reportLowMemory) {
14337 app.reportLowMemory = false;
14338 app.thread.scheduleLowMemory();
14339 } else {
14340 app.thread.processInBackground();
14341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014342 }
14343 } catch (Exception e) {
14344 // whatever.
14345 }
14346 }
14347
14348 /**
14349 * Returns true if things are idle enough to perform GCs.
14350 */
Josh Bartel7f208742010-02-25 11:01:44 -060014351 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014352 boolean processingBroadcasts = false;
14353 for (BroadcastQueue q : mBroadcastQueues) {
14354 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14355 processingBroadcasts = true;
14356 }
14357 }
14358 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014359 && (mSleeping || (mMainStack.mResumedActivity != null &&
14360 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014361 }
14362
14363 /**
14364 * Perform GCs on all processes that are waiting for it, but only
14365 * if things are idle.
14366 */
14367 final void performAppGcsLocked() {
14368 final int N = mProcessesToGc.size();
14369 if (N <= 0) {
14370 return;
14371 }
Josh Bartel7f208742010-02-25 11:01:44 -060014372 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014373 while (mProcessesToGc.size() > 0) {
14374 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014375 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014376 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14377 <= SystemClock.uptimeMillis()) {
14378 // To avoid spamming the system, we will GC processes one
14379 // at a time, waiting a few seconds between each.
14380 performAppGcLocked(proc);
14381 scheduleAppGcsLocked();
14382 return;
14383 } else {
14384 // It hasn't been long enough since we last GCed this
14385 // process... put it in the list to wait for its time.
14386 addProcessToGcListLocked(proc);
14387 break;
14388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014389 }
14390 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014391
14392 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014393 }
14394 }
14395
14396 /**
14397 * If all looks good, perform GCs on all processes waiting for them.
14398 */
14399 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014400 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014401 performAppGcsLocked();
14402 return;
14403 }
14404 // Still not idle, wait some more.
14405 scheduleAppGcsLocked();
14406 }
14407
14408 /**
14409 * Schedule the execution of all pending app GCs.
14410 */
14411 final void scheduleAppGcsLocked() {
14412 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014413
14414 if (mProcessesToGc.size() > 0) {
14415 // Schedule a GC for the time to the next process.
14416 ProcessRecord proc = mProcessesToGc.get(0);
14417 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14418
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014419 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014420 long now = SystemClock.uptimeMillis();
14421 if (when < (now+GC_TIMEOUT)) {
14422 when = now + GC_TIMEOUT;
14423 }
14424 mHandler.sendMessageAtTime(msg, when);
14425 }
14426 }
14427
14428 /**
14429 * Add a process to the array of processes waiting to be GCed. Keeps the
14430 * list in sorted order by the last GC time. The process can't already be
14431 * on the list.
14432 */
14433 final void addProcessToGcListLocked(ProcessRecord proc) {
14434 boolean added = false;
14435 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14436 if (mProcessesToGc.get(i).lastRequestedGc <
14437 proc.lastRequestedGc) {
14438 added = true;
14439 mProcessesToGc.add(i+1, proc);
14440 break;
14441 }
14442 }
14443 if (!added) {
14444 mProcessesToGc.add(0, proc);
14445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014446 }
14447
14448 /**
14449 * Set up to ask a process to GC itself. This will either do it
14450 * immediately, or put it on the list of processes to gc the next
14451 * time things are idle.
14452 */
14453 final void scheduleAppGcLocked(ProcessRecord app) {
14454 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014455 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014456 return;
14457 }
14458 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014459 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014460 scheduleAppGcsLocked();
14461 }
14462 }
14463
Dianne Hackborn287952c2010-09-22 22:34:31 -070014464 final void checkExcessivePowerUsageLocked(boolean doKills) {
14465 updateCpuStatsNow();
14466
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014467 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014468 boolean doWakeKills = doKills;
14469 boolean doCpuKills = doKills;
14470 if (mLastPowerCheckRealtime == 0) {
14471 doWakeKills = false;
14472 }
14473 if (mLastPowerCheckUptime == 0) {
14474 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014475 }
14476 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014477 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014478 }
14479 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014480 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14481 final long curUptime = SystemClock.uptimeMillis();
14482 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14483 mLastPowerCheckRealtime = curRealtime;
14484 mLastPowerCheckUptime = curUptime;
14485 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14486 doWakeKills = false;
14487 }
14488 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14489 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014490 }
14491 int i = mLruProcesses.size();
14492 while (i > 0) {
14493 i--;
14494 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014495 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014496 long wtime;
14497 synchronized (stats) {
14498 wtime = stats.getProcessWakeTime(app.info.uid,
14499 app.pid, curRealtime);
14500 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014501 long wtimeUsed = wtime - app.lastWakeTime;
14502 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14503 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014504 StringBuilder sb = new StringBuilder(128);
14505 sb.append("Wake for ");
14506 app.toShortString(sb);
14507 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014508 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014509 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014510 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014511 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014512 sb.append((wtimeUsed*100)/realtimeSince);
14513 sb.append("%)");
14514 Slog.i(TAG, sb.toString());
14515 sb.setLength(0);
14516 sb.append("CPU for ");
14517 app.toShortString(sb);
14518 sb.append(": over ");
14519 TimeUtils.formatDuration(uptimeSince, sb);
14520 sb.append(" used ");
14521 TimeUtils.formatDuration(cputimeUsed, sb);
14522 sb.append(" (");
14523 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014524 sb.append("%)");
14525 Slog.i(TAG, sb.toString());
14526 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014527 // If a process has held a wake lock for more
14528 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014529 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014530 if (doWakeKills && realtimeSince > 0
14531 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14532 synchronized (stats) {
14533 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14534 realtimeSince, wtimeUsed);
14535 }
14536 Slog.w(TAG, "Excessive wake lock in " + app.processName
14537 + " (pid " + app.pid + "): held " + wtimeUsed
14538 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014539 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14540 app.processName, app.setAdj, "excessive wake lock");
14541 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014542 } else if (doCpuKills && uptimeSince > 0
14543 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14544 synchronized (stats) {
14545 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14546 uptimeSince, cputimeUsed);
14547 }
14548 Slog.w(TAG, "Excessive CPU in " + app.processName
14549 + " (pid " + app.pid + "): used " + cputimeUsed
14550 + " during " + uptimeSince);
14551 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14552 app.processName, app.setAdj, "excessive cpu");
14553 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014554 } else {
14555 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014556 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014557 }
14558 }
14559 }
14560 }
14561
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014562 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014563 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014564 app.hiddenAdj = hiddenAdj;
14565
14566 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014567 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014568 }
14569
Dianne Hackborn287952c2010-09-22 22:34:31 -070014570 final boolean wasKeeping = app.keeping;
14571
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014572 boolean success = true;
14573
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014574 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014575
Jeff Brown10e89712011-07-08 18:52:57 -070014576 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070014577 if (wasKeeping && !app.keeping) {
14578 // This app is no longer something we want to keep. Note
14579 // its current wake lock time to later know to kill it if
14580 // it is not behaving well.
14581 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14582 synchronized (stats) {
14583 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14584 app.pid, SystemClock.elapsedRealtime());
14585 }
14586 app.lastCpuTime = app.curCpuTime;
14587 }
14588
14589 app.setRawAdj = app.curRawAdj;
14590 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014591
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014592 if (app.curAdj != app.setAdj) {
14593 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014594 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014595 TAG, "Set " + app.pid + " " + app.processName +
14596 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014597 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014598 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014599 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014600 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014601 }
14602 }
14603 if (app.setSchedGroup != app.curSchedGroup) {
14604 app.setSchedGroup = app.curSchedGroup;
14605 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14606 "Setting process group of " + app.processName
14607 + " to " + app.curSchedGroup);
14608 if (app.waitingToKill != null &&
14609 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14610 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14611 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14612 app.processName, app.setAdj, app.waitingToKill);
14613 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014614 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014615 } else {
14616 if (true) {
14617 long oldId = Binder.clearCallingIdentity();
14618 try {
14619 Process.setProcessGroup(app.pid, app.curSchedGroup);
14620 } catch (Exception e) {
14621 Slog.w(TAG, "Failed setting process group of " + app.pid
14622 + " to " + app.curSchedGroup);
14623 e.printStackTrace();
14624 } finally {
14625 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014626 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014627 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014628 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014629 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014630 app.thread.setSchedulingGroup(app.curSchedGroup);
14631 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014632 }
14633 }
14634 }
14635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014636 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014637 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014638 }
14639
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014640 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014641 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014642 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014643 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014644 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014645 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014646 }
14647 }
14648 return resumedActivity;
14649 }
14650
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014651 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014652 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014653 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14654 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014655 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14656 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014657
14658 mAdjSeq++;
14659
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014660 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014661 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14662 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014663 if (nowHidden != wasHidden) {
14664 // Changed to/from hidden state, so apps after it in the LRU
14665 // list may also be changed.
14666 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014667 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014668 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014669 }
14670
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014671 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014672 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014673 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14674
14675 if (false) {
14676 RuntimeException e = new RuntimeException();
14677 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014678 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014679 }
14680
14681 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014682 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014683
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014684 // Let's determine how many processes we have running vs.
14685 // how many slots we have for background processes; we may want
14686 // to put multiple processes in a slot of there are enough of
14687 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014688 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014689 int factor = (mLruProcesses.size()-4)/numSlots;
14690 if (factor < 1) factor = 1;
14691 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014692 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014693 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014694
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014695 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014696 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014697 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014698 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014699 while (i > 0) {
14700 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014701 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014702 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014703 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14704 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014705 && app.curAdj == curHiddenAdj) {
14706 step++;
14707 if (step >= factor) {
14708 step = 0;
14709 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014710 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014711 }
14712 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014713 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014714 numHidden++;
14715 if (numHidden > mProcessLimit) {
14716 Slog.i(TAG, "No longer want " + app.processName
14717 + " (pid " + app.pid + "): hidden #" + numHidden);
14718 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14719 app.processName, app.setAdj, "too many background");
14720 app.killedBackground = true;
14721 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014722 }
14723 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014724 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14725 // If this is an isolated process, and there are no
14726 // services running in it, then the process is no longer
14727 // needed. We agressively kill these because we can by
14728 // definition not re-use the same process again, and it is
14729 // good to avoid having whatever code was running in them
14730 // left sitting around after no longer needed.
14731 Slog.i(TAG, "Isolated process " + app.processName
14732 + " (pid " + app.pid + ") no longer needed");
14733 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14734 app.processName, app.setAdj, "isolated not needed");
14735 app.killedBackground = true;
14736 Process.killProcessQuiet(app.pid);
14737 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014738 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14739 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14740 && !app.killedBackground) {
14741 numTrimming++;
14742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014743 }
14744 }
14745
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014746 mNumServiceProcs = mNewNumServiceProcs;
14747
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014748 // Now determine the memory trimming level of background processes.
14749 // Unfortunately we need to start at the back of the list to do this
14750 // properly. We only do this if the number of background apps we
14751 // are managing to keep around is less than half the maximum we desire;
14752 // if we are keeping a good number around, we'll let them use whatever
14753 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014754 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014755 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014756 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014757 int minFactor = 2;
14758 if (mHomeProcess != null) minFactor++;
14759 if (mPreviousProcess != null) minFactor++;
14760 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014761 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014762 int fgTrimLevel;
14763 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14764 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14765 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14766 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14767 } else {
14768 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14769 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014770 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014771 for (i=0; i<N; i++) {
14772 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014773 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14774 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014775 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014776 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14777 try {
14778 app.thread.scheduleTrimMemory(curLevel);
14779 } catch (RemoteException e) {
14780 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014781 if (false) {
14782 // For now we won't do this; our memory trimming seems
14783 // to be good enough at this point that destroying
14784 // activities causes more harm than good.
14785 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14786 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014787 // Need to do this on its own message because the stack may not
14788 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014789 // For these apps we will also finish their activities
14790 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014791 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014792 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014793 }
14794 }
14795 app.trimMemoryLevel = curLevel;
14796 step++;
14797 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014798 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014799 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014800 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14801 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014802 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014803 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14804 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014805 break;
14806 }
14807 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014808 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014809 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014810 && app.thread != null) {
14811 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014812 app.thread.scheduleTrimMemory(
14813 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014814 } catch (RemoteException e) {
14815 }
14816 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014817 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014818 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014819 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014820 && app.pendingUiClean) {
14821 // If this application is now in the background and it
14822 // had done UI, then give it the special trim level to
14823 // have it free UI resources.
14824 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14825 if (app.trimMemoryLevel < level && app.thread != null) {
14826 try {
14827 app.thread.scheduleTrimMemory(level);
14828 } catch (RemoteException e) {
14829 }
14830 }
14831 app.pendingUiClean = false;
14832 }
14833 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014834 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014835 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014836 } catch (RemoteException e) {
14837 }
14838 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014839 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014840 }
14841 }
14842 } else {
14843 final int N = mLruProcesses.size();
14844 for (i=0; i<N; i++) {
14845 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014846 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014847 && app.pendingUiClean) {
14848 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14849 && app.thread != null) {
14850 try {
14851 app.thread.scheduleTrimMemory(
14852 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14853 } catch (RemoteException e) {
14854 }
14855 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014856 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014857 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014858 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014859 }
14860 }
14861
14862 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014863 // Need to do this on its own message because the stack may not
14864 // be in a consistent state at this point.
14865 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014867 }
14868
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014869 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014870 synchronized (this) {
14871 int i;
14872
14873 // First remove any unused application processes whose package
14874 // has been removed.
14875 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14876 final ProcessRecord app = mRemovedProcesses.get(i);
14877 if (app.activities.size() == 0
14878 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014879 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014880 TAG, "Exiting empty application process "
14881 + app.processName + " ("
14882 + (app.thread != null ? app.thread.asBinder() : null)
14883 + ")\n");
14884 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014885 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14886 app.processName, app.setAdj, "empty");
14887 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014888 } else {
14889 try {
14890 app.thread.scheduleExit();
14891 } catch (Exception e) {
14892 // Ignore exceptions.
14893 }
14894 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014895 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014896 mRemovedProcesses.remove(i);
14897
14898 if (app.persistent) {
14899 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014900 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014901 }
14902 }
14903 }
14904 }
14905
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014906 // Now update the oom adj for all processes.
14907 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014908 }
14909 }
14910
14911 /** This method sends the specified signal to each of the persistent apps */
14912 public void signalPersistentProcesses(int sig) throws RemoteException {
14913 if (sig != Process.SIGNAL_USR1) {
14914 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14915 }
14916
14917 synchronized (this) {
14918 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14919 != PackageManager.PERMISSION_GRANTED) {
14920 throw new SecurityException("Requires permission "
14921 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14922 }
14923
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014924 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14925 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014926 if (r.thread != null && r.persistent) {
14927 Process.sendSignal(r.pid, sig);
14928 }
14929 }
14930 }
14931 }
14932
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014933 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14934 if (proc == null || proc == mProfileProc) {
14935 proc = mProfileProc;
14936 path = mProfileFile;
14937 profileType = mProfileType;
14938 clearProfilerLocked();
14939 }
14940 if (proc == null) {
14941 return;
14942 }
14943 try {
14944 proc.thread.profilerControl(false, path, null, profileType);
14945 } catch (RemoteException e) {
14946 throw new IllegalStateException("Process disappeared");
14947 }
14948 }
14949
14950 private void clearProfilerLocked() {
14951 if (mProfileFd != null) {
14952 try {
14953 mProfileFd.close();
14954 } catch (IOException e) {
14955 }
14956 }
14957 mProfileApp = null;
14958 mProfileProc = null;
14959 mProfileFile = null;
14960 mProfileType = 0;
14961 mAutoStopProfiler = false;
14962 }
14963
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014964 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014965 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014966
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014967 try {
14968 synchronized (this) {
14969 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14970 // its own permission.
14971 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14972 != PackageManager.PERMISSION_GRANTED) {
14973 throw new SecurityException("Requires permission "
14974 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014975 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014976
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014977 if (start && fd == null) {
14978 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014979 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014980
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014981 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014982 if (process != null) {
14983 try {
14984 int pid = Integer.parseInt(process);
14985 synchronized (mPidsSelfLocked) {
14986 proc = mPidsSelfLocked.get(pid);
14987 }
14988 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014989 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014990
14991 if (proc == null) {
14992 HashMap<String, SparseArray<ProcessRecord>> all
14993 = mProcessNames.getMap();
14994 SparseArray<ProcessRecord> procs = all.get(process);
14995 if (procs != null && procs.size() > 0) {
14996 proc = procs.valueAt(0);
14997 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014998 }
14999 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015000
15001 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015002 throw new IllegalArgumentException("Unknown process: " + process);
15003 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015004
15005 if (start) {
15006 stopProfilerLocked(null, null, 0);
15007 setProfileApp(proc.info, proc.processName, path, fd, false);
15008 mProfileProc = proc;
15009 mProfileType = profileType;
15010 try {
15011 fd = fd.dup();
15012 } catch (IOException e) {
15013 fd = null;
15014 }
15015 proc.thread.profilerControl(start, path, fd, profileType);
15016 fd = null;
15017 mProfileFd = null;
15018 } else {
15019 stopProfilerLocked(proc, path, profileType);
15020 if (fd != null) {
15021 try {
15022 fd.close();
15023 } catch (IOException e) {
15024 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015025 }
15026 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015027
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015028 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015029 }
15030 } catch (RemoteException e) {
15031 throw new IllegalStateException("Process disappeared");
15032 } finally {
15033 if (fd != null) {
15034 try {
15035 fd.close();
15036 } catch (IOException e) {
15037 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015038 }
15039 }
15040 }
Andy McFadden824c5102010-07-09 16:26:57 -070015041
15042 public boolean dumpHeap(String process, boolean managed,
15043 String path, ParcelFileDescriptor fd) throws RemoteException {
15044
15045 try {
15046 synchronized (this) {
15047 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
15048 // its own permission (same as profileControl).
15049 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
15050 != PackageManager.PERMISSION_GRANTED) {
15051 throw new SecurityException("Requires permission "
15052 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
15053 }
15054
15055 if (fd == null) {
15056 throw new IllegalArgumentException("null fd");
15057 }
15058
15059 ProcessRecord proc = null;
15060 try {
15061 int pid = Integer.parseInt(process);
15062 synchronized (mPidsSelfLocked) {
15063 proc = mPidsSelfLocked.get(pid);
15064 }
15065 } catch (NumberFormatException e) {
15066 }
15067
15068 if (proc == null) {
15069 HashMap<String, SparseArray<ProcessRecord>> all
15070 = mProcessNames.getMap();
15071 SparseArray<ProcessRecord> procs = all.get(process);
15072 if (procs != null && procs.size() > 0) {
15073 proc = procs.valueAt(0);
15074 }
15075 }
15076
15077 if (proc == null || proc.thread == null) {
15078 throw new IllegalArgumentException("Unknown process: " + process);
15079 }
15080
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080015081 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
15082 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070015083 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
15084 throw new SecurityException("Process not debuggable: " + proc);
15085 }
15086 }
15087
15088 proc.thread.dumpHeap(managed, path, fd);
15089 fd = null;
15090 return true;
15091 }
15092 } catch (RemoteException e) {
15093 throw new IllegalStateException("Process disappeared");
15094 } finally {
15095 if (fd != null) {
15096 try {
15097 fd.close();
15098 } catch (IOException e) {
15099 }
15100 }
15101 }
15102 }
15103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015104 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
15105 public void monitor() {
15106 synchronized (this) { }
15107 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080015108
Dianne Hackborna573f6a2012-02-09 16:12:18 -080015109 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080015110 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
15111 ProcessRecord processRecord = mLruProcesses.get(i);
15112 try {
15113 if (processRecord.thread != null) {
15114 processRecord.thread.setCoreSettings(settings);
15115 }
15116 } catch (RemoteException re) {
15117 /* ignore */
15118 }
15119 }
15120 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015121
15122 // Multi-user methods
15123
Amith Yamasani742a6712011-05-04 14:49:28 -070015124 private int mCurrentUserId;
15125 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
15126
15127 public boolean switchUser(int userId) {
15128 final int callingUid = Binder.getCallingUid();
15129 if (callingUid != 0 && callingUid != Process.myUid()) {
15130 Slog.e(TAG, "Trying to switch user from unauthorized app");
15131 return false;
15132 }
15133 if (mCurrentUserId == userId)
15134 return true;
15135
15136 synchronized (this) {
15137 // Check if user is already logged in, otherwise check if user exists first before
15138 // adding to the list of logged in users.
15139 if (mLoggedInUsers.indexOfKey(userId) < 0) {
15140 if (!userExists(userId)) {
15141 return false;
15142 }
15143 mLoggedInUsers.append(userId, userId);
15144 }
15145
15146 mCurrentUserId = userId;
15147 boolean haveActivities = mMainStack.switchUser(userId);
15148 if (!haveActivities) {
15149 startHomeActivityLocked(userId);
15150 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080015151
Amith Yamasani37ce3a82012-02-06 12:04:42 -080015152 }
Amith Yamasani13593602012-03-22 16:16:17 -070015153
15154 // Inform of user switch
15155 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
15156 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
15157 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
15158
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015159 return true;
15160 }
Amith Yamasani742a6712011-05-04 14:49:28 -070015161
Amith Yamasani52f1d752012-03-28 18:19:29 -070015162 @Override
15163 public UserInfo getCurrentUser() throws RemoteException {
15164 final int callingUid = Binder.getCallingUid();
15165 if (callingUid != 0 && callingUid != Process.myUid()) {
15166 Slog.e(TAG, "Trying to get user from unauthorized app");
15167 return null;
15168 }
15169 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
15170 }
15171
Amith Yamasani13593602012-03-22 16:16:17 -070015172 private void onUserRemoved(Intent intent) {
15173 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
15174 if (extraUserId < 1) return;
15175
15176 // Kill all the processes for the user
15177 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
15178 synchronized (this) {
15179 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
15180 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
15181 SparseArray<ProcessRecord> uids = uidMap.getValue();
15182 for (int i = 0; i < uids.size(); i++) {
15183 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
15184 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
15185 }
15186 }
15187 }
15188
15189 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
15190 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
15191 false, false, true, true, extraUserId);
15192 }
15193 }
15194 }
15195
Amith Yamasani742a6712011-05-04 14:49:28 -070015196 private boolean userExists(int userId) {
15197 try {
Amith Yamasani13593602012-03-22 16:16:17 -070015198 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
15199 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070015200 } catch (RemoteException re) {
15201 // Won't happen, in same process
15202 }
15203
15204 return false;
15205 }
15206
Amith Yamasani37ce3a82012-02-06 12:04:42 -080015207 private void checkValidCaller(int uid, int userId) {
15208 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
15209
15210 throw new SecurityException("Caller uid=" + uid
15211 + " is not privileged to communicate with user=" + userId);
15212 }
Amith Yamasani742a6712011-05-04 14:49:28 -070015213
15214 private int applyUserId(int uid, int userId) {
15215 return UserId.getUid(userId, uid);
15216 }
15217
15218 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080015219 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070015220 ApplicationInfo newInfo = new ApplicationInfo(info);
15221 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070015222 newInfo.dataDir = USER_DATA_DIR + userId + "/"
15223 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070015224 return newInfo;
15225 }
15226
15227 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070015228 if (aInfo == null
15229 || (userId < 1 && aInfo.applicationInfo.uid < UserId.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070015230 return aInfo;
15231 }
15232
15233 ActivityInfo info = new ActivityInfo(aInfo);
15234 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
15235 return info;
15236 }
15237
15238 static class ServiceMap {
15239
15240 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
15241 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
15242 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
15243 mServicesByIntentPerUser = new SparseArray<
15244 HashMap<Intent.FilterComparison, ServiceRecord>>();
15245
15246 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
15247 // TODO: Deal with global services
15248 if (DEBUG_MU)
15249 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
15250 return getServices(callingUser).get(name);
15251 }
15252
15253 ServiceRecord getServiceByName(ComponentName name) {
15254 return getServiceByName(name, -1);
15255 }
15256
15257 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15258 // TODO: Deal with global services
15259 if (DEBUG_MU)
15260 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
15261 return getServicesByIntent(callingUser).get(filter);
15262 }
15263
15264 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
15265 return getServiceByIntent(filter, -1);
15266 }
15267
15268 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
15269 // TODO: Deal with global services
15270 getServices(callingUser).put(name, value);
15271 }
15272
15273 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
15274 ServiceRecord value) {
15275 // TODO: Deal with global services
15276 getServicesByIntent(callingUser).put(filter, value);
15277 }
15278
15279 void removeServiceByName(ComponentName name, int callingUser) {
15280 // TODO: Deal with global services
15281 ServiceRecord removed = getServices(callingUser).remove(name);
15282 if (DEBUG_MU)
15283 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
15284 + " removed=" + removed);
15285 }
15286
15287 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15288 // TODO: Deal with global services
15289 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15290 if (DEBUG_MU)
15291 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15292 + " removed=" + removed);
15293 }
15294
15295 Collection<ServiceRecord> getAllServices(int callingUser) {
15296 // TODO: Deal with global services
15297 return getServices(callingUser).values();
15298 }
15299
15300 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15301 HashMap map = mServicesByNamePerUser.get(callingUser);
15302 if (map == null) {
15303 map = new HashMap<ComponentName, ServiceRecord>();
15304 mServicesByNamePerUser.put(callingUser, map);
15305 }
15306 return map;
15307 }
15308
15309 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15310 int callingUser) {
15311 HashMap map = mServicesByIntentPerUser.get(callingUser);
15312 if (map == null) {
15313 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15314 mServicesByIntentPerUser.put(callingUser, map);
15315 }
15316 return map;
15317 }
15318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015319}