blob: 3b4200ab02a1c40dba5567ff4e8ed79eda84fa23 [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
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700516 protected BroadcastFilter[] newArray(int size) {
517 return new BroadcastFilter[size];
518 }
519
520 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700521 protected String packageForFilter(BroadcastFilter filter) {
522 return filter.packageName;
523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 };
525
526 /**
527 * State of all active sticky broadcasts. Keys are the action of the
528 * sticky Intent, values are an ArrayList of all broadcasted intents with
529 * that action (which should usually be one).
530 */
531 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
532 new HashMap<String, ArrayList<Intent>>();
533
Amith Yamasani742a6712011-05-04 14:49:28 -0700534 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800535
536 /**
537 * All currently bound service connections. Keys are the IBinder of
538 * the client's IServiceConnection.
539 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700540 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
541 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800542
543 /**
544 * List of services that we have been asked to start,
545 * but haven't yet been able to. It is used to hold start requests
546 * while waiting for their corresponding application thread to get
547 * going.
548 */
549 final ArrayList<ServiceRecord> mPendingServices
550 = new ArrayList<ServiceRecord>();
551
552 /**
553 * List of services that are scheduled to restart following a crash.
554 */
555 final ArrayList<ServiceRecord> mRestartingServices
556 = new ArrayList<ServiceRecord>();
557
558 /**
559 * List of services that are in the process of being stopped.
560 */
561 final ArrayList<ServiceRecord> mStoppingServices
562 = new ArrayList<ServiceRecord>();
563
564 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700565 * Backup/restore process management
566 */
567 String mBackupAppName = null;
568 BackupRecord mBackupTarget = null;
569
570 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 * List of PendingThumbnailsRecord objects of clients who are still
572 * waiting to receive all of the thumbnails for a task.
573 */
574 final ArrayList mPendingThumbnails = new ArrayList();
575
576 /**
577 * List of HistoryRecord objects that have been finished and must
578 * still report back to a pending thumbnail receiver.
579 */
580 final ArrayList mCancelledThumbnails = new ArrayList();
581
Amith Yamasani742a6712011-05-04 14:49:28 -0700582 final ProviderMap mProviderMap = new ProviderMap();
583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 /**
585 * List of content providers who have clients waiting for them. The
586 * application is currently being launched and the provider will be
587 * removed from this list once it is published.
588 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700589 final ArrayList<ContentProviderRecord> mLaunchingProviders
590 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591
592 /**
593 * Global set of specific Uri permissions that have been granted.
594 */
595 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
596 = new SparseArray<HashMap<Uri, UriPermission>>();
597
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800598 CoreSettingsObserver mCoreSettingsObserver;
599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 /**
601 * Thread-local storage used to carry caller permissions over through
602 * indirect content-provider access.
603 * @see #ActivityManagerService.openContentUri()
604 */
605 private class Identity {
606 public int pid;
607 public int uid;
608
609 Identity(int _pid, int _uid) {
610 pid = _pid;
611 uid = _uid;
612 }
613 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
616
617 /**
618 * All information we have collected about the runtime performance of
619 * any user id that can impact battery performance.
620 */
621 final BatteryStatsService mBatteryStatsService;
622
623 /**
624 * information about component usage
625 */
626 final UsageStatsService mUsageStatsService;
627
628 /**
629 * Current configuration information. HistoryRecord objects are given
630 * a reference to this object to indicate which configuration they are
631 * currently running in, so this object must be kept immutable.
632 */
633 Configuration mConfiguration = new Configuration();
634
635 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800636 * Current sequencing integer of the configuration, for skipping old
637 * configurations.
638 */
639 int mConfigurationSeq = 0;
640
641 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700642 * Hardware-reported OpenGLES version.
643 */
644 final int GL_ES_VERSION;
645
646 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 * List of initialization arguments to pass to all processes when binding applications to them.
648 * For example, references to the commonly used services.
649 */
650 HashMap<String, IBinder> mAppBindArgs;
651
652 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700653 * Temporary to avoid allocations. Protected by main lock.
654 */
655 final StringBuilder mStringBuilder = new StringBuilder(256);
656
657 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658 * Used to control how we initialize the service.
659 */
660 boolean mStartRunning = false;
661 ComponentName mTopComponent;
662 String mTopAction;
663 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700664 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800665 boolean mSystemReady = false;
666 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700667 boolean mWaitingUpdate = false;
668 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700669 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700670 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800671
672 Context mContext;
673
674 int mFactoryTest;
675
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700676 boolean mCheckedForSetup;
677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800678 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700679 * The time at which we will allow normal application switches again,
680 * after a call to {@link #stopAppSwitches()}.
681 */
682 long mAppSwitchesAllowedTime;
683
684 /**
685 * This is set to true after the first switch after mAppSwitchesAllowedTime
686 * is set; any switches after that will clear the time.
687 */
688 boolean mDidAppSwitch;
689
690 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700691 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700692 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700693 long mLastPowerCheckRealtime;
694
695 /**
696 * Last time (in uptime) at which we checked for power usage.
697 */
698 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700699
700 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 * Set while we are wanting to sleep, to prevent any
702 * activities from being started/resumed.
703 */
704 boolean mSleeping = false;
705
706 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700707 * State of external calls telling us if the device is asleep.
708 */
709 boolean mWentToSleep = false;
710
711 /**
712 * State of external call telling us if the lock screen is shown.
713 */
714 boolean mLockScreenShown = false;
715
716 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700717 * Set if we are shutting down the system, similar to sleeping.
718 */
719 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720
721 /**
722 * Task identifier that activities are currently being started
723 * in. Incremented each time a new task is created.
724 * todo: Replace this with a TokenSpace class that generates non-repeating
725 * integers that won't wrap.
726 */
727 int mCurTask = 1;
728
729 /**
730 * Current sequence id for oom_adj computation traversal.
731 */
732 int mAdjSeq = 0;
733
734 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700735 * Current sequence id for process LRU updating.
736 */
737 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738
739 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700740 * Keep track of the number of service processes we last found, to
741 * determine on the next iteration which should be B services.
742 */
743 int mNumServiceProcs = 0;
744 int mNewNumServiceProcs = 0;
745
746 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 * System monitoring: number of processes that died since the last
748 * N procs were started.
749 */
750 int[] mProcDeaths = new int[20];
751
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700752 /**
753 * This is set if we had to do a delayed dexopt of an app before launching
754 * it, to increasing the ANR timeouts in that case.
755 */
756 boolean mDidDexOpt;
757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 String mDebugApp = null;
759 boolean mWaitForDebugger = false;
760 boolean mDebugTransient = false;
761 String mOrigDebugApp = null;
762 boolean mOrigWaitForDebugger = false;
763 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700764 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700765 String mProfileApp = null;
766 ProcessRecord mProfileProc = null;
767 String mProfileFile;
768 ParcelFileDescriptor mProfileFd;
769 int mProfileType = 0;
770 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800771 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800772
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700773 static class ProcessChangeItem {
774 static final int CHANGE_ACTIVITIES = 1<<0;
775 static final int CHANGE_IMPORTANCE= 1<<1;
776 int changes;
777 int uid;
778 int pid;
779 int importance;
780 boolean foregroundActivities;
781 }
782
Jeff Sharkeya4620792011-05-20 15:29:23 -0700783 final RemoteCallbackList<IProcessObserver> mProcessObservers
784 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700785 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
786
787 final ArrayList<ProcessChangeItem> mPendingProcessChanges
788 = new ArrayList<ProcessChangeItem>();
789 final ArrayList<ProcessChangeItem> mAvailProcessChanges
790 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 /**
793 * Callback of last caller to {@link #requestPss}.
794 */
795 Runnable mRequestPssCallback;
796
797 /**
798 * Remaining processes for which we are waiting results from the last
799 * call to {@link #requestPss}.
800 */
801 final ArrayList<ProcessRecord> mRequestPssList
802 = new ArrayList<ProcessRecord>();
803
804 /**
805 * Runtime statistics collection thread. This object's lock is used to
806 * protect all related state.
807 */
808 final Thread mProcessStatsThread;
809
810 /**
811 * Used to collect process stats when showing not responding dialog.
812 * Protected by mProcessStatsThread.
813 */
814 final ProcessStats mProcessStats = new ProcessStats(
815 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700816 final AtomicLong mLastCpuTime = new AtomicLong(0);
817 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 long mLastWriteTime = 0;
820
821 /**
822 * Set to true after the system has finished booting.
823 */
824 boolean mBooted = false;
825
Dianne Hackborn7d608422011-08-07 16:24:18 -0700826 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700827 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828
829 WindowManagerService mWindowManager;
830
831 static ActivityManagerService mSelf;
832 static ActivityThread mSystemThread;
833
834 private final class AppDeathRecipient implements IBinder.DeathRecipient {
835 final ProcessRecord mApp;
836 final int mPid;
837 final IApplicationThread mAppThread;
838
839 AppDeathRecipient(ProcessRecord app, int pid,
840 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800841 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 TAG, "New death recipient " + this
843 + " for thread " + thread.asBinder());
844 mApp = app;
845 mPid = pid;
846 mAppThread = thread;
847 }
848
849 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800850 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 TAG, "Death received in " + this
852 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 synchronized(ActivityManagerService.this) {
854 appDiedLocked(mApp, mPid, mAppThread);
855 }
856 }
857 }
858
859 static final int SHOW_ERROR_MSG = 1;
860 static final int SHOW_NOT_RESPONDING_MSG = 2;
861 static final int SHOW_FACTORY_ERROR_MSG = 3;
862 static final int UPDATE_CONFIGURATION_MSG = 4;
863 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
864 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 static final int SERVICE_TIMEOUT_MSG = 12;
866 static final int UPDATE_TIME_ZONE = 13;
867 static final int SHOW_UID_ERROR_MSG = 14;
868 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700870 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700871 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800872 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700873 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
874 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700875 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700876 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700877 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700878 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700879 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700880 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700881 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700882 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800884 static final int FIRST_ACTIVITY_STACK_MSG = 100;
885 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
886 static final int FIRST_COMPAT_MODE_MSG = 300;
887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700889 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700890 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891
892 final Handler mHandler = new Handler() {
893 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800894 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 //}
896
897 public void handleMessage(Message msg) {
898 switch (msg.what) {
899 case SHOW_ERROR_MSG: {
900 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800901 synchronized (ActivityManagerService.this) {
902 ProcessRecord proc = (ProcessRecord)data.get("app");
903 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800904 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 return;
906 }
907 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700908 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800909 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800910 d.show();
911 proc.crashDialog = d;
912 } else {
913 // The device is asleep, so just pretend that the user
914 // saw a crash dialog and hit "force quit".
915 res.set(0);
916 }
917 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700918
919 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 } break;
921 case SHOW_NOT_RESPONDING_MSG: {
922 synchronized (ActivityManagerService.this) {
923 HashMap data = (HashMap) msg.obj;
924 ProcessRecord proc = (ProcessRecord)data.get("app");
925 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800926 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 return;
928 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800929
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700930 Intent intent = new Intent("android.intent.action.ANR");
931 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800932 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
933 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700934 }
935 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800936 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700937 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800938
Justin Kohbc52ca22012-03-29 15:11:44 -0700939 if (mShowDialogs) {
940 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700941 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700942 d.show();
943 proc.anrDialog = d;
944 } else {
945 // Just kill the app if there is no dialog to be shown.
946 killAppAtUsersRequest(proc, null);
947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800948 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700949
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700950 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800951 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700952 case SHOW_STRICT_MODE_VIOLATION_MSG: {
953 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
954 synchronized (ActivityManagerService.this) {
955 ProcessRecord proc = (ProcessRecord) data.get("app");
956 if (proc == null) {
957 Slog.e(TAG, "App not found when showing strict mode dialog.");
958 break;
959 }
960 if (proc.crashDialog != null) {
961 Slog.e(TAG, "App already has strict mode dialog: " + proc);
962 return;
963 }
964 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700965 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700966 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
967 d.show();
968 proc.crashDialog = d;
969 } else {
970 // The device is asleep, so just pretend that the user
971 // saw a crash dialog and hit "force quit".
972 res.set(0);
973 }
974 }
975 ensureBootCompleted();
976 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 case SHOW_FACTORY_ERROR_MSG: {
978 Dialog d = new FactoryErrorDialog(
979 mContext, msg.getData().getCharSequence("msg"));
980 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700981 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 } break;
983 case UPDATE_CONFIGURATION_MSG: {
984 final ContentResolver resolver = mContext.getContentResolver();
985 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
986 } break;
987 case GC_BACKGROUND_PROCESSES_MSG: {
988 synchronized (ActivityManagerService.this) {
989 performAppGcsIfAppropriateLocked();
990 }
991 } break;
992 case WAIT_FOR_DEBUGGER_MSG: {
993 synchronized (ActivityManagerService.this) {
994 ProcessRecord app = (ProcessRecord)msg.obj;
995 if (msg.arg1 != 0) {
996 if (!app.waitedForDebugger) {
997 Dialog d = new AppWaitingForDebuggerDialog(
998 ActivityManagerService.this,
999 mContext, app);
1000 app.waitDialog = d;
1001 app.waitedForDebugger = true;
1002 d.show();
1003 }
1004 } else {
1005 if (app.waitDialog != null) {
1006 app.waitDialog.dismiss();
1007 app.waitDialog = null;
1008 }
1009 }
1010 }
1011 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001013 if (mDidDexOpt) {
1014 mDidDexOpt = false;
1015 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1016 nmsg.obj = msg.obj;
1017 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
1018 return;
1019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 serviceTimeout((ProcessRecord)msg.obj);
1021 } break;
1022 case UPDATE_TIME_ZONE: {
1023 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001024 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1025 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 if (r.thread != null) {
1027 try {
1028 r.thread.updateTimeZone();
1029 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001030 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 }
1032 }
1033 }
1034 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001035 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001036 case CLEAR_DNS_CACHE: {
1037 synchronized (ActivityManagerService.this) {
1038 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1039 ProcessRecord r = mLruProcesses.get(i);
1040 if (r.thread != null) {
1041 try {
1042 r.thread.clearDnsCache();
1043 } catch (RemoteException ex) {
1044 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1045 }
1046 }
1047 }
1048 }
1049 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001050 case UPDATE_HTTP_PROXY: {
1051 ProxyProperties proxy = (ProxyProperties)msg.obj;
1052 String host = "";
1053 String port = "";
1054 String exclList = "";
1055 if (proxy != null) {
1056 host = proxy.getHost();
1057 port = Integer.toString(proxy.getPort());
1058 exclList = proxy.getExclusionList();
1059 }
1060 synchronized (ActivityManagerService.this) {
1061 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1062 ProcessRecord r = mLruProcesses.get(i);
1063 if (r.thread != null) {
1064 try {
1065 r.thread.setHttpProxy(host, port, exclList);
1066 } catch (RemoteException ex) {
1067 Slog.w(TAG, "Failed to update http proxy for: " +
1068 r.info.processName);
1069 }
1070 }
1071 }
1072 }
1073 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001075 String title = "System UIDs Inconsistent";
1076 String text = "UIDs on the system are inconsistent, you need to wipe your"
1077 + " data partition or your device will be unstable.";
1078 Log.e(TAG, title + ": " + text);
1079 if (mShowDialogs) {
1080 // XXX This is a temporary dialog, no need to localize.
1081 AlertDialog d = new BaseErrorDialog(mContext);
1082 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1083 d.setCancelable(false);
1084 d.setTitle(title);
1085 d.setMessage(text);
1086 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1087 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1088 mUidAlert = d;
1089 d.show();
1090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 } break;
1092 case IM_FEELING_LUCKY_MSG: {
1093 if (mUidAlert != null) {
1094 mUidAlert.dismiss();
1095 mUidAlert = null;
1096 }
1097 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001099 if (mDidDexOpt) {
1100 mDidDexOpt = false;
1101 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1102 nmsg.obj = msg.obj;
1103 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1104 return;
1105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 ProcessRecord app = (ProcessRecord)msg.obj;
1107 synchronized (ActivityManagerService.this) {
1108 processStartTimedOutLocked(app);
1109 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001110 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001111 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1112 synchronized (ActivityManagerService.this) {
1113 doPendingActivityLaunchesLocked(true);
1114 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001115 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001116 case KILL_APPLICATION_MSG: {
1117 synchronized (ActivityManagerService.this) {
1118 int uid = msg.arg1;
1119 boolean restart = (msg.arg2 == 1);
1120 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001121 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1122 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001123 }
1124 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001125 case FINALIZE_PENDING_INTENT_MSG: {
1126 ((PendingIntentRecord)msg.obj).completeFinalize();
1127 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001128 case POST_HEAVY_NOTIFICATION_MSG: {
1129 INotificationManager inm = NotificationManager.getService();
1130 if (inm == null) {
1131 return;
1132 }
1133
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001134 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001135 ProcessRecord process = root.app;
1136 if (process == null) {
1137 return;
1138 }
1139
1140 try {
1141 Context context = mContext.createPackageContext(process.info.packageName, 0);
1142 String text = mContext.getString(R.string.heavy_weight_notification,
1143 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1144 Notification notification = new Notification();
1145 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1146 notification.when = 0;
1147 notification.flags = Notification.FLAG_ONGOING_EVENT;
1148 notification.tickerText = text;
1149 notification.defaults = 0; // please be quiet
1150 notification.sound = null;
1151 notification.vibrate = null;
1152 notification.setLatestEventInfo(context, text,
1153 mContext.getText(R.string.heavy_weight_notification_detail),
1154 PendingIntent.getActivity(mContext, 0, root.intent,
1155 PendingIntent.FLAG_CANCEL_CURRENT));
1156
1157 try {
1158 int[] outId = new int[1];
1159 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1160 notification, outId);
1161 } catch (RuntimeException e) {
1162 Slog.w(ActivityManagerService.TAG,
1163 "Error showing notification for heavy-weight app", e);
1164 } catch (RemoteException e) {
1165 }
1166 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001167 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001168 }
1169 } break;
1170 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1171 INotificationManager inm = NotificationManager.getService();
1172 if (inm == null) {
1173 return;
1174 }
1175 try {
1176 inm.cancelNotification("android",
1177 R.string.heavy_weight_notification);
1178 } catch (RuntimeException e) {
1179 Slog.w(ActivityManagerService.TAG,
1180 "Error canceling notification for service", e);
1181 } catch (RemoteException e) {
1182 }
1183 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001184 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1185 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001186 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001187 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001188 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1189 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001190 }
1191 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001192 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1193 synchronized (ActivityManagerService.this) {
1194 ActivityRecord ar = (ActivityRecord)msg.obj;
1195 if (mCompatModeDialog != null) {
1196 if (mCompatModeDialog.mAppInfo.packageName.equals(
1197 ar.info.applicationInfo.packageName)) {
1198 return;
1199 }
1200 mCompatModeDialog.dismiss();
1201 mCompatModeDialog = null;
1202 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001203 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001204 if (mCompatModePackages.getPackageAskCompatModeLocked(
1205 ar.packageName)) {
1206 int mode = mCompatModePackages.computeCompatModeLocked(
1207 ar.info.applicationInfo);
1208 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1209 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1210 mCompatModeDialog = new CompatModeDialog(
1211 ActivityManagerService.this, mContext,
1212 ar.info.applicationInfo);
1213 mCompatModeDialog.show();
1214 }
1215 }
1216 }
1217 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001218 break;
1219 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001220 case DISPATCH_PROCESSES_CHANGED: {
1221 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001222 break;
1223 }
1224 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001225 final int pid = msg.arg1;
1226 final int uid = msg.arg2;
1227 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001228 break;
1229 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001230 case REPORT_MEM_USAGE: {
1231 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1232 if (!isDebuggable) {
1233 return;
1234 }
1235 synchronized (ActivityManagerService.this) {
1236 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001237 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1238 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001239 // avoid spamming.
1240 return;
1241 }
1242 mLastMemUsageReportTime = now;
1243 }
1244 Thread thread = new Thread() {
1245 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001246 StringBuilder dropBuilder = new StringBuilder(1024);
1247 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001248 StringWriter oomSw = new StringWriter();
1249 PrintWriter oomPw = new PrintWriter(oomSw);
1250 StringWriter catSw = new StringWriter();
1251 PrintWriter catPw = new PrintWriter(catSw);
1252 String[] emptyArgs = new String[] { };
1253 StringBuilder tag = new StringBuilder(128);
1254 StringBuilder stack = new StringBuilder(128);
1255 tag.append("Low on memory -- ");
1256 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1257 tag, stack);
1258 dropBuilder.append(stack);
1259 dropBuilder.append('\n');
1260 dropBuilder.append('\n');
1261 String oomString = oomSw.toString();
1262 dropBuilder.append(oomString);
1263 dropBuilder.append('\n');
1264 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001265 try {
1266 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1267 "procrank", });
1268 final InputStreamReader converter = new InputStreamReader(
1269 proc.getInputStream());
1270 BufferedReader in = new BufferedReader(converter);
1271 String line;
1272 while (true) {
1273 line = in.readLine();
1274 if (line == null) {
1275 break;
1276 }
1277 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001278 logBuilder.append(line);
1279 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001280 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001281 dropBuilder.append(line);
1282 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001283 }
1284 converter.close();
1285 } catch (IOException e) {
1286 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001287 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001288 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001289 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001290 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001291 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001292 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001293 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001294 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001295 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001296 addErrorToDropBox("lowmem", null, "system_server", null,
1297 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001298 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001299 synchronized (ActivityManagerService.this) {
1300 long now = SystemClock.uptimeMillis();
1301 if (mLastMemUsageReportTime < now) {
1302 mLastMemUsageReportTime = now;
1303 }
1304 }
1305 }
1306 };
1307 thread.start();
1308 break;
1309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 }
1311 }
1312 };
1313
1314 public static void setSystemProcess() {
1315 try {
1316 ActivityManagerService m = mSelf;
1317
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001318 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001320 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001321 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 if (MONITOR_CPU_USAGE) {
1323 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 ServiceManager.addService("permission", new PermissionController(m));
1326
1327 ApplicationInfo info =
1328 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001329 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001330 mSystemThread.installSystemApplicationInfo(info);
1331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 synchronized (mSelf) {
1333 ProcessRecord app = mSelf.newProcessRecordLocked(
1334 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001335 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001337 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001338 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001339 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 synchronized (mSelf.mPidsSelfLocked) {
1341 mSelf.mPidsSelfLocked.put(app.pid, app);
1342 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001343 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 }
1345 } catch (PackageManager.NameNotFoundException e) {
1346 throw new RuntimeException(
1347 "Unable to find android system package", e);
1348 }
1349 }
1350
1351 public void setWindowManager(WindowManagerService wm) {
1352 mWindowManager = wm;
1353 }
1354
1355 public static final Context main(int factoryTest) {
1356 AThread thr = new AThread();
1357 thr.start();
1358
1359 synchronized (thr) {
1360 while (thr.mService == null) {
1361 try {
1362 thr.wait();
1363 } catch (InterruptedException e) {
1364 }
1365 }
1366 }
1367
1368 ActivityManagerService m = thr.mService;
1369 mSelf = m;
1370 ActivityThread at = ActivityThread.systemMain();
1371 mSystemThread = at;
1372 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001373 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 m.mContext = context;
1375 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001376 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377
1378 m.mBatteryStatsService.publish(context);
1379 m.mUsageStatsService.publish(context);
1380
1381 synchronized (thr) {
1382 thr.mReady = true;
1383 thr.notifyAll();
1384 }
1385
1386 m.startRunning(null, null, null, null);
1387
1388 return context;
1389 }
1390
1391 public static ActivityManagerService self() {
1392 return mSelf;
1393 }
1394
1395 static class AThread extends Thread {
1396 ActivityManagerService mService;
1397 boolean mReady = false;
1398
1399 public AThread() {
1400 super("ActivityManager");
1401 }
1402
1403 public void run() {
1404 Looper.prepare();
1405
1406 android.os.Process.setThreadPriority(
1407 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001408 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409
1410 ActivityManagerService m = new ActivityManagerService();
1411
1412 synchronized (this) {
1413 mService = m;
1414 notifyAll();
1415 }
1416
1417 synchronized (this) {
1418 while (!mReady) {
1419 try {
1420 wait();
1421 } catch (InterruptedException e) {
1422 }
1423 }
1424 }
1425
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001426 // For debug builds, log event loop stalls to dropbox for analysis.
1427 if (StrictMode.conditionallyEnableDebugLogging()) {
1428 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1429 }
1430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001431 Looper.loop();
1432 }
1433 }
1434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 static class MemBinder extends Binder {
1436 ActivityManagerService mActivityManagerService;
1437 MemBinder(ActivityManagerService activityManagerService) {
1438 mActivityManagerService = activityManagerService;
1439 }
1440
1441 @Override
1442 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001443 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1444 != PackageManager.PERMISSION_GRANTED) {
1445 pw.println("Permission Denial: can't dump meminfo from from pid="
1446 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1447 + " without permission " + android.Manifest.permission.DUMP);
1448 return;
1449 }
1450
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001451 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001452 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 }
1454 }
1455
Chet Haase9c1e23b2011-03-24 10:51:31 -07001456 static class GraphicsBinder extends Binder {
1457 ActivityManagerService mActivityManagerService;
1458 GraphicsBinder(ActivityManagerService activityManagerService) {
1459 mActivityManagerService = activityManagerService;
1460 }
1461
1462 @Override
1463 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001464 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1465 != PackageManager.PERMISSION_GRANTED) {
1466 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1467 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1468 + " without permission " + android.Manifest.permission.DUMP);
1469 return;
1470 }
1471
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001472 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001473 }
1474 }
1475
Jeff Brown6754ba22011-12-14 20:20:01 -08001476 static class DbBinder extends Binder {
1477 ActivityManagerService mActivityManagerService;
1478 DbBinder(ActivityManagerService activityManagerService) {
1479 mActivityManagerService = activityManagerService;
1480 }
1481
1482 @Override
1483 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1484 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1485 != PackageManager.PERMISSION_GRANTED) {
1486 pw.println("Permission Denial: can't dump dbinfo from from pid="
1487 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1488 + " without permission " + android.Manifest.permission.DUMP);
1489 return;
1490 }
1491
1492 mActivityManagerService.dumpDbInfo(fd, pw, args);
1493 }
1494 }
1495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 static class CpuBinder extends Binder {
1497 ActivityManagerService mActivityManagerService;
1498 CpuBinder(ActivityManagerService activityManagerService) {
1499 mActivityManagerService = activityManagerService;
1500 }
1501
1502 @Override
1503 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001504 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1505 != PackageManager.PERMISSION_GRANTED) {
1506 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1507 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1508 + " without permission " + android.Manifest.permission.DUMP);
1509 return;
1510 }
1511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001513 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1514 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1515 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517 }
1518 }
1519
1520 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001521 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001522
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001523 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1524 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1525 mBroadcastQueues[0] = mFgBroadcastQueue;
1526 mBroadcastQueues[1] = mBgBroadcastQueue;
1527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 File dataDir = Environment.getDataDirectory();
1529 File systemDir = new File(dataDir, "system");
1530 systemDir.mkdirs();
1531 mBatteryStatsService = new BatteryStatsService(new File(
1532 systemDir, "batterystats.bin").toString());
1533 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001534 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001535 mOnBattery = DEBUG_POWER ? true
1536 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001537 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001539 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001540 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001541 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542
Jack Palevichb90d28c2009-07-22 15:35:24 -07001543 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1544 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1545
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001546 mConfiguration.setToDefaults();
1547 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001548 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 mProcessStats.init();
1550
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001551 mCompatModePackages = new CompatModePackages(this, systemDir);
1552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 // Add ourself to the Watchdog monitors.
1554 Watchdog.getInstance().addMonitor(this);
1555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 mProcessStatsThread = new Thread("ProcessStats") {
1557 public void run() {
1558 while (true) {
1559 try {
1560 try {
1561 synchronized(this) {
1562 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001563 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001565 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 // + ", write delay=" + nextWriteDelay);
1567 if (nextWriteDelay < nextCpuDelay) {
1568 nextCpuDelay = nextWriteDelay;
1569 }
1570 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001571 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 this.wait(nextCpuDelay);
1573 }
1574 }
1575 } catch (InterruptedException e) {
1576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 updateCpuStatsNow();
1578 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001579 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 }
1581 }
1582 }
1583 };
1584 mProcessStatsThread.start();
1585 }
1586
1587 @Override
1588 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1589 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001590 if (code == SYSPROPS_TRANSACTION) {
1591 // We need to tell all apps about the system property change.
1592 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1593 synchronized(this) {
1594 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1595 final int NA = apps.size();
1596 for (int ia=0; ia<NA; ia++) {
1597 ProcessRecord app = apps.valueAt(ia);
1598 if (app.thread != null) {
1599 procs.add(app.thread.asBinder());
1600 }
1601 }
1602 }
1603 }
1604
1605 int N = procs.size();
1606 for (int i=0; i<N; i++) {
1607 Parcel data2 = Parcel.obtain();
1608 try {
1609 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1610 } catch (RemoteException e) {
1611 }
1612 data2.recycle();
1613 }
1614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 try {
1616 return super.onTransact(code, data, reply, flags);
1617 } catch (RuntimeException e) {
1618 // The activity manager only throws security exceptions, so let's
1619 // log all others.
1620 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001621 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 }
1623 throw e;
1624 }
1625 }
1626
1627 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001628 final long now = SystemClock.uptimeMillis();
1629 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1630 return;
1631 }
1632 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1633 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 mProcessStatsThread.notify();
1635 }
1636 }
1637 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 void updateCpuStatsNow() {
1640 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001641 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 final long now = SystemClock.uptimeMillis();
1643 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001646 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1647 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 haveNewCpuStats = true;
1649 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001650 //Slog.i(TAG, mProcessStats.printCurrentState());
1651 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 // + mProcessStats.getTotalCpuPercent() + "%");
1653
Joe Onorato8a9b2202010-02-26 18:56:32 -08001654 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 if ("true".equals(SystemProperties.get("events.cpu"))) {
1656 int user = mProcessStats.getLastUserTime();
1657 int system = mProcessStats.getLastSystemTime();
1658 int iowait = mProcessStats.getLastIoWaitTime();
1659 int irq = mProcessStats.getLastIrqTime();
1660 int softIrq = mProcessStats.getLastSoftIrqTime();
1661 int idle = mProcessStats.getLastIdleTime();
1662
1663 int total = user + system + iowait + irq + softIrq + idle;
1664 if (total == 0) total = 1;
1665
Doug Zongker2bec3d42009-12-04 12:52:44 -08001666 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 ((user+system+iowait+irq+softIrq) * 100) / total,
1668 (user * 100) / total,
1669 (system * 100) / total,
1670 (iowait * 100) / total,
1671 (irq * 100) / total,
1672 (softIrq * 100) / total);
1673 }
1674 }
1675
Amith Yamasanie43530a2009-08-21 13:11:37 -07001676 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001677 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001678 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001679 synchronized(mPidsSelfLocked) {
1680 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001681 if (mOnBattery) {
1682 int perc = bstats.startAddingCpuLocked();
1683 int totalUTime = 0;
1684 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001685 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001687 ProcessStats.Stats st = mProcessStats.getStats(i);
1688 if (!st.working) {
1689 continue;
1690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001692 int otherUTime = (st.rel_utime*perc)/100;
1693 int otherSTime = (st.rel_stime*perc)/100;
1694 totalUTime += otherUTime;
1695 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 if (pr != null) {
1697 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001698 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1699 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001700 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001701 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001702 } else {
1703 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001704 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001705 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001706 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1707 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001708 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 }
1711 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001712 bstats.finishAddingCpuLocked(perc, totalUTime,
1713 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
1715 }
1716 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1719 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001720 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 }
1722 }
1723 }
1724 }
1725
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001726 @Override
1727 public void batteryNeedsCpuUpdate() {
1728 updateCpuStatsNow();
1729 }
1730
1731 @Override
1732 public void batteryPowerChanged(boolean onBattery) {
1733 // When plugging in, update the CPU stats first before changing
1734 // the plug state.
1735 updateCpuStatsNow();
1736 synchronized (this) {
1737 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001738 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001739 }
1740 }
1741 }
1742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 /**
1744 * Initialize the application bind args. These are passed to each
1745 * process when the bindApplication() IPC is sent to the process. They're
1746 * lazily setup to make sure the services are running when they're asked for.
1747 */
1748 private HashMap<String, IBinder> getCommonServicesLocked() {
1749 if (mAppBindArgs == null) {
1750 mAppBindArgs = new HashMap<String, IBinder>();
1751
1752 // Setup the application init args
1753 mAppBindArgs.put("package", ServiceManager.getService("package"));
1754 mAppBindArgs.put("window", ServiceManager.getService("window"));
1755 mAppBindArgs.put(Context.ALARM_SERVICE,
1756 ServiceManager.getService(Context.ALARM_SERVICE));
1757 }
1758 return mAppBindArgs;
1759 }
1760
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001761 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 if (mFocusedActivity != r) {
1763 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001764 if (r != null) {
1765 mWindowManager.setFocusedApp(r.appToken, true);
1766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 }
1768 }
1769
Dianne Hackborn906497c2010-05-10 15:57:38 -07001770 private final void updateLruProcessInternalLocked(ProcessRecord app,
1771 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001773 int lrui = mLruProcesses.indexOf(app);
1774 if (lrui >= 0) mLruProcesses.remove(lrui);
1775
1776 int i = mLruProcesses.size()-1;
1777 int skipTop = 0;
1778
Dianne Hackborn906497c2010-05-10 15:57:38 -07001779 app.lruSeq = mLruSeq;
1780
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001781 // compute the new weight for this process.
1782 if (updateActivityTime) {
1783 app.lastActivityTime = SystemClock.uptimeMillis();
1784 }
1785 if (app.activities.size() > 0) {
1786 // If this process has activities, we more strongly want to keep
1787 // it around.
1788 app.lruWeight = app.lastActivityTime;
1789 } else if (app.pubProviders.size() > 0) {
1790 // If this process contains content providers, we want to keep
1791 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001792 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001793 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001794 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001795 } else {
1796 // If this process doesn't have activities, we less strongly
1797 // want to keep it around, and generally want to avoid getting
1798 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001799 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001800 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001801 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001802 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001803
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001804 while (i >= 0) {
1805 ProcessRecord p = mLruProcesses.get(i);
1806 // If this app shouldn't be in front of the first N background
1807 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001808 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001809 skipTop--;
1810 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001811 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001812 mLruProcesses.add(i+1, app);
1813 break;
1814 }
1815 i--;
1816 }
1817 if (i < 0) {
1818 mLruProcesses.add(0, app);
1819 }
1820
Dianne Hackborn906497c2010-05-10 15:57:38 -07001821 // If the app is currently using a content provider or service,
1822 // bump those processes as well.
1823 if (app.connections.size() > 0) {
1824 for (ConnectionRecord cr : app.connections) {
1825 if (cr.binding != null && cr.binding.service != null
1826 && cr.binding.service.app != null
1827 && cr.binding.service.app.lruSeq != mLruSeq) {
Björn Davidsson90f9e312010-11-18 08:26:27 +01001828 updateLruProcessInternalLocked(cr.binding.service.app, false,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001829 updateActivityTime, i+1);
1830 }
1831 }
1832 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001833 for (int j=app.conProviders.size()-1; j>=0; j--) {
1834 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1835 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Jean-Baptiste Querub8c64052012-06-11 11:01:19 -07001836 updateLruProcessInternalLocked(cpr.proc, false,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001837 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001838 }
1839 }
1840
Joe Onorato8a9b2202010-02-26 18:56:32 -08001841 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 if (oomAdj) {
1843 updateOomAdjLocked();
1844 }
1845 }
1846
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001847 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001848 boolean oomAdj, boolean updateActivityTime) {
1849 mLruSeq++;
1850 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1851 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001852
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001853 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001855 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001856 // The system gets to run in any process. If there are multiple
1857 // processes with the same uid, just pick the first (this
1858 // should never happen).
1859 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1860 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001861 if (procs == null) return null;
1862 final int N = procs.size();
1863 for (int i = 0; i < N; i++) {
1864 if (UserId.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
1865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 }
1867 ProcessRecord proc = mProcessNames.get(processName, uid);
1868 return proc;
1869 }
1870
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001871 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001872 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001873 try {
1874 if (pm.performDexOpt(packageName)) {
1875 mDidDexOpt = true;
1876 }
1877 } catch (RemoteException e) {
1878 }
1879 }
1880
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001881 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 int transit = mWindowManager.getPendingAppTransition();
1883 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1884 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1885 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1886 }
1887
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001888 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001890 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1891 boolean isolated) {
1892 ProcessRecord app;
1893 if (!isolated) {
1894 app = getProcessRecordLocked(processName, info.uid);
1895 } else {
1896 // If this is an isolated process, it can't re-use an existing process.
1897 app = null;
1898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 // We don't have to do anything more if:
1900 // (1) There is an existing application record; and
1901 // (2) The caller doesn't think it is dead, OR there is no thread
1902 // object attached to it so we know it couldn't have crashed; and
1903 // (3) There is a pid assigned to it, so it is either starting or
1904 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001905 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 + " app=" + app + " knownToBeDead=" + knownToBeDead
1907 + " thread=" + (app != null ? app.thread : null)
1908 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001909 if (app != null && app.pid > 0) {
1910 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001911 // We already have the app running, or are waiting for it to
1912 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001913 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001914 // If this is a new package in the process, add the package to the list
1915 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001916 return app;
1917 } else {
1918 // An application record is attached to a previous process,
1919 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001920 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001921 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 String hostingNameStr = hostingName != null
1926 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001927
1928 if (!isolated) {
1929 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1930 // If we are in the background, then check to see if this process
1931 // is bad. If so, we will just silently fail.
1932 if (mBadProcesses.get(info.processName, info.uid) != null) {
1933 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1934 + "/" + info.processName);
1935 return null;
1936 }
1937 } else {
1938 // When the user is explicitly starting a process, then clear its
1939 // crash count so that we won't make it bad until they see at
1940 // least one crash dialog again, and make the process good again
1941 // if it had been bad.
1942 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001943 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001944 mProcessCrashTimes.remove(info.processName, info.uid);
1945 if (mBadProcesses.get(info.processName, info.uid) != null) {
1946 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1947 info.processName);
1948 mBadProcesses.remove(info.processName, info.uid);
1949 if (app != null) {
1950 app.bad = false;
1951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 }
1953 }
1954 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001957 app = newProcessRecordLocked(null, info, processName, isolated);
1958 if (app == null) {
1959 Slog.w(TAG, "Failed making new process record for "
1960 + processName + "/" + info.uid + " isolated=" + isolated);
1961 return null;
1962 }
1963 mProcessNames.put(processName, app.uid, app);
1964 if (isolated) {
1965 mIsolatedProcesses.put(app.uid, app);
1966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 } else {
1968 // If this is a new package in the process, add the package to the list
1969 app.addPackage(info.packageName);
1970 }
1971
1972 // If the system is not ready yet, then hold off on starting this
1973 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001974 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001975 && !isAllowedWhileBooting(info)
1976 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 if (!mProcessesOnHold.contains(app)) {
1978 mProcessesOnHold.add(app);
1979 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001980 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 return app;
1982 }
1983
1984 startProcessLocked(app, hostingType, hostingNameStr);
1985 return (app.pid != 0) ? app : null;
1986 }
1987
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001988 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1989 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1990 }
1991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 private final void startProcessLocked(ProcessRecord app,
1993 String hostingType, String hostingNameStr) {
1994 if (app.pid > 0 && app.pid != MY_PID) {
1995 synchronized (mPidsSelfLocked) {
1996 mPidsSelfLocked.remove(app.pid);
1997 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1998 }
1999 app.pid = 0;
2000 }
2001
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07002002 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
2003 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 mProcessesOnHold.remove(app);
2005
2006 updateCpuStats();
2007
2008 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2009 mProcDeaths[0] = 0;
2010
2011 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002012 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002015 if (!app.isolated) {
2016 try {
2017 gids = mContext.getPackageManager().getPackageGids(
2018 app.info.packageName);
2019 } catch (PackageManager.NameNotFoundException e) {
2020 Slog.w(TAG, "Unable to retrieve gids", e);
2021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 }
2023 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2024 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2025 && mTopComponent != null
2026 && app.processName.equals(mTopComponent.getPackageName())) {
2027 uid = 0;
2028 }
2029 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2030 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2031 uid = 0;
2032 }
2033 }
2034 int debugFlags = 0;
2035 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2036 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002037 // Also turn on CheckJNI for debuggable apps. It's quite
2038 // awkward to turn on otherwise.
2039 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002041 // Run the app in safe mode if its manifest requests so or the
2042 // system is booted in safe mode.
2043 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2044 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002045 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2048 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2049 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002050 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2051 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 if ("1".equals(SystemProperties.get("debug.assert"))) {
2054 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2055 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002056
2057 // Start the process. It will either succeed and return a result containing
2058 // the PID of the new process, or else throw a RuntimeException.
2059 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002060 app.processName, uid, uid, gids, debugFlags,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002061 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2064 synchronized (bs) {
2065 if (bs.isOnBattery()) {
2066 app.batteryStats.incStartsLocked();
2067 }
2068 }
2069
Jeff Brown3f9dd282011-07-08 20:02:19 -07002070 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 app.processName, hostingType,
2072 hostingNameStr != null ? hostingNameStr : "");
2073
2074 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002075 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 }
2077
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002078 StringBuilder buf = mStringBuilder;
2079 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 buf.append("Start proc ");
2081 buf.append(app.processName);
2082 buf.append(" for ");
2083 buf.append(hostingType);
2084 if (hostingNameStr != null) {
2085 buf.append(" ");
2086 buf.append(hostingNameStr);
2087 }
2088 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002089 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 buf.append(" uid=");
2091 buf.append(uid);
2092 buf.append(" gids={");
2093 if (gids != null) {
2094 for (int gi=0; gi<gids.length; gi++) {
2095 if (gi != 0) buf.append(", ");
2096 buf.append(gids[gi]);
2097
2098 }
2099 }
2100 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002101 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002102 app.pid = startResult.pid;
2103 app.usingWrapper = startResult.usingWrapper;
2104 app.removed = false;
2105 synchronized (mPidsSelfLocked) {
2106 this.mPidsSelfLocked.put(startResult.pid, app);
2107 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2108 msg.obj = app;
2109 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2110 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 }
2112 } catch (RuntimeException e) {
2113 // XXX do better error recovery.
2114 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002115 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 }
2117 }
2118
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002119 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 if (resumed) {
2121 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2122 } else {
2123 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2124 }
2125 }
2126
Amith Yamasani742a6712011-05-04 14:49:28 -07002127 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002128 if (mHeadless) {
2129 // Added because none of the other calls to ensureBootCompleted seem to fire
2130 // when running headless.
2131 ensureBootCompleted();
2132 return false;
2133 }
2134
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002135 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2136 && mTopAction == null) {
2137 // We are running in factory test mode, but unable to find
2138 // the factory test app, so just sit around displaying the
2139 // error message and don't try to start anything.
2140 return false;
2141 }
2142 Intent intent = new Intent(
2143 mTopAction,
2144 mTopData != null ? Uri.parse(mTopData) : null);
2145 intent.setComponent(mTopComponent);
2146 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2147 intent.addCategory(Intent.CATEGORY_HOME);
2148 }
2149 ActivityInfo aInfo =
2150 intent.resolveActivityInfo(mContext.getPackageManager(),
2151 STOCK_PM_FLAGS);
2152 if (aInfo != null) {
2153 intent.setComponent(new ComponentName(
2154 aInfo.applicationInfo.packageName, aInfo.name));
2155 // Don't do this if the home app is currently being
2156 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002157 aInfo = new ActivityInfo(aInfo);
2158 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002159 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2160 aInfo.applicationInfo.uid);
2161 if (app == null || app.instrumentationClass == null) {
2162 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002163 mMainStack.startActivityLocked(null, intent, null, aInfo,
2164 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002165 }
2166 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002167
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002168 return true;
2169 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002170
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002171 /**
2172 * Starts the "new version setup screen" if appropriate.
2173 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002174 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002175 // Only do this once per boot.
2176 if (mCheckedForSetup) {
2177 return;
2178 }
2179
2180 // We will show this screen if the current one is a different
2181 // version than the last one shown, and we are not running in
2182 // low-level factory test mode.
2183 final ContentResolver resolver = mContext.getContentResolver();
2184 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2185 Settings.Secure.getInt(resolver,
2186 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2187 mCheckedForSetup = true;
2188
2189 // See if we should be showing the platform update setup UI.
2190 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2191 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2192 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2193
2194 // We don't allow third party apps to replace this.
2195 ResolveInfo ri = null;
2196 for (int i=0; ris != null && i<ris.size(); i++) {
2197 if ((ris.get(i).activityInfo.applicationInfo.flags
2198 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2199 ri = ris.get(i);
2200 break;
2201 }
2202 }
2203
2204 if (ri != null) {
2205 String vers = ri.activityInfo.metaData != null
2206 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2207 : null;
2208 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2209 vers = ri.activityInfo.applicationInfo.metaData.getString(
2210 Intent.METADATA_SETUP_VERSION);
2211 }
2212 String lastVers = Settings.Secure.getString(
2213 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2214 if (vers != null && !vers.equals(lastVers)) {
2215 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2216 intent.setComponent(new ComponentName(
2217 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002218 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2219 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002220 }
2221 }
2222 }
2223 }
2224
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002225 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002226 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002227 }
2228
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002229 void enforceNotIsolatedCaller(String caller) {
2230 if (UserId.isIsolated(Binder.getCallingUid())) {
2231 throw new SecurityException("Isolated process not allowed to call " + caller);
2232 }
2233 }
2234
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002235 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002236 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002237 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002238 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2239 }
2240 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002241
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002242 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002243 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2244 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002245 synchronized (this) {
2246 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2247 }
2248 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002249
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002250 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002251 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002252 synchronized (this) {
2253 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2254 }
2255 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002256
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002257 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002258 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2259 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002260 synchronized (this) {
2261 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002262 }
2263 }
2264
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002265 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002266 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002267 synchronized (this) {
2268 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2269 }
2270 }
2271
2272 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002273 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2274 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002275 synchronized (this) {
2276 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2277 }
2278 }
2279
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002280 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002281 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002282 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002285 private void dispatchProcessesChanged() {
2286 int N;
2287 synchronized (this) {
2288 N = mPendingProcessChanges.size();
2289 if (mActiveProcessChanges.length < N) {
2290 mActiveProcessChanges = new ProcessChangeItem[N];
2291 }
2292 mPendingProcessChanges.toArray(mActiveProcessChanges);
2293 mAvailProcessChanges.addAll(mPendingProcessChanges);
2294 mPendingProcessChanges.clear();
2295 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2296 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002297 int i = mProcessObservers.beginBroadcast();
2298 while (i > 0) {
2299 i--;
2300 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2301 if (observer != null) {
2302 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002303 for (int j=0; j<N; j++) {
2304 ProcessChangeItem item = mActiveProcessChanges[j];
2305 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2306 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2307 + item.pid + " uid=" + item.uid + ": "
2308 + item.foregroundActivities);
2309 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2310 item.foregroundActivities);
2311 }
2312 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2313 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2314 + item.pid + " uid=" + item.uid + ": " + item.importance);
2315 observer.onImportanceChanged(item.pid, item.uid,
2316 item.importance);
2317 }
2318 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002319 } catch (RemoteException e) {
2320 }
2321 }
2322 }
2323 mProcessObservers.finishBroadcast();
2324 }
2325
2326 private void dispatchProcessDied(int pid, int uid) {
2327 int i = mProcessObservers.beginBroadcast();
2328 while (i > 0) {
2329 i--;
2330 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2331 if (observer != null) {
2332 try {
2333 observer.onProcessDied(pid, uid);
2334 } catch (RemoteException e) {
2335 }
2336 }
2337 }
2338 mProcessObservers.finishBroadcast();
2339 }
2340
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002341 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002342 final int N = mPendingActivityLaunches.size();
2343 if (N <= 0) {
2344 return;
2345 }
2346 for (int i=0; i<N; i++) {
2347 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002348 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002349 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002350 }
2351 mPendingActivityLaunches.clear();
2352 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002353
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002354 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002355 Intent intent, String resolvedType, IBinder resultTo,
2356 String resultWho, int requestCode, int startFlags,
2357 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002358 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002359 int userId = 0;
2360 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2361 // Requesting home, set the identity to the current user
2362 // HACK!
2363 userId = mCurrentUserId;
2364 } else {
2365 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2366 // the current user's userId
2367 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2368 userId = 0;
2369 } else {
2370 userId = Binder.getOrigCallingUser();
2371 }
2372 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002373 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002374 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2375 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002376 }
2377
2378 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002379 Intent intent, String resolvedType, IBinder resultTo,
2380 String resultWho, int requestCode, int startFlags, String profileFile,
2381 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002382 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002383 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002384 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002385 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002386 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2387 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002388 return res;
2389 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002390
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002391 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002392 Intent intent, String resolvedType, IBinder resultTo,
2393 String resultWho, int requestCode, int startFlags, Configuration config,
2394 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002395 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002396 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002397 resultTo, resultWho, requestCode, startFlags,
2398 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002399 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002400 }
2401
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002402 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002403 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002404 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002405 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002406 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002407 // Refuse possible leaked file descriptors
2408 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2409 throw new IllegalArgumentException("File descriptors passed in Intent");
2410 }
2411
2412 IIntentSender sender = intent.getTarget();
2413 if (!(sender instanceof PendingIntentRecord)) {
2414 throw new IllegalArgumentException("Bad PendingIntent object");
2415 }
2416
2417 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002418
2419 synchronized (this) {
2420 // If this is coming from the currently resumed activity, it is
2421 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002422 if (mMainStack.mResumedActivity != null
2423 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002424 Binder.getCallingUid()) {
2425 mAppSwitchesAllowedTime = 0;
2426 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002427 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002428 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2429 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002430 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002431 }
2432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002434 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 // Refuse possible leaked file descriptors
2436 if (intent != null && intent.hasFileDescriptors() == true) {
2437 throw new IllegalArgumentException("File descriptors passed in Intent");
2438 }
2439
2440 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002441 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2442 if (r == null) {
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 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 if (r.app == null || r.app.thread == null) {
2447 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002448 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 return false;
2450 }
2451 intent = new Intent(intent);
2452 // The caller is not allowed to change the data.
2453 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2454 // And we are resetting to find the next component...
2455 intent.setComponent(null);
2456
2457 ActivityInfo aInfo = null;
2458 try {
2459 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002460 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002462 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2463 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002464
2465 // Look for the original activity in the list...
2466 final int N = resolves != null ? resolves.size() : 0;
2467 for (int i=0; i<N; i++) {
2468 ResolveInfo rInfo = resolves.get(i);
2469 if (rInfo.activityInfo.packageName.equals(r.packageName)
2470 && rInfo.activityInfo.name.equals(r.info.name)) {
2471 // We found the current one... the next matching is
2472 // after it.
2473 i++;
2474 if (i<N) {
2475 aInfo = resolves.get(i).activityInfo;
2476 }
2477 break;
2478 }
2479 }
2480 } catch (RemoteException e) {
2481 }
2482
2483 if (aInfo == null) {
2484 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002485 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 return false;
2487 }
2488
2489 intent.setComponent(new ComponentName(
2490 aInfo.applicationInfo.packageName, aInfo.name));
2491 intent.setFlags(intent.getFlags()&~(
2492 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2493 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2494 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2495 Intent.FLAG_ACTIVITY_NEW_TASK));
2496
2497 // Okay now we need to start the new activity, replacing the
2498 // currently running activity. This is a little tricky because
2499 // we want to start the new one as if the current one is finished,
2500 // but not finish the current one first so that there is no flicker.
2501 // And thus...
2502 final boolean wasFinishing = r.finishing;
2503 r.finishing = true;
2504
2505 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002506 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 final String resultWho = r.resultWho;
2508 final int requestCode = r.requestCode;
2509 r.resultTo = null;
2510 if (resultTo != null) {
2511 resultTo.removeResultsLocked(r, resultWho, requestCode);
2512 }
2513
2514 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002515 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002516 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2517 resultWho, requestCode, -1, r.launchedFromUid, 0,
2518 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 Binder.restoreCallingIdentity(origId);
2520
2521 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002522 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 return false;
2524 }
2525 return true;
2526 }
2527 }
2528
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002529 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002531 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002532
2533 // This is so super not safe, that only the system (or okay root)
2534 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002535 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002536 final int callingUid = Binder.getCallingUid();
2537 if (callingUid != 0 && callingUid != Process.myUid()) {
2538 throw new SecurityException(
2539 "startActivityInPackage only available to the system");
2540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541
Amith Yamasani742a6712011-05-04 14:49:28 -07002542 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002543 resultTo, resultWho, requestCode, startFlags,
2544 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002545 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002546 }
2547
2548 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002549 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002550 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002551 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002552 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002553 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002554 }
2555
2556 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002557 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2558 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002559
2560 // This is so super not safe, that only the system (or okay root)
2561 // can do it.
2562 final int callingUid = Binder.getCallingUid();
2563 if (callingUid != 0 && callingUid != Process.myUid()) {
2564 throw new SecurityException(
2565 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002567 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002568 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002569 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 }
2571
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002572 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002574 // Quick case: check if the top-most recent task is the same.
2575 if (N > 0 && mRecentTasks.get(0) == task) {
2576 return;
2577 }
2578 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 for (int i=0; i<N; i++) {
2580 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002581 if (task.userId == tr.userId
2582 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2583 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 mRecentTasks.remove(i);
2585 i--;
2586 N--;
2587 if (task.intent == null) {
2588 // If the new recent task we are adding is not fully
2589 // specified, then replace it with the existing recent task.
2590 task = tr;
2591 }
2592 }
2593 }
2594 if (N >= MAX_RECENT_TASKS) {
2595 mRecentTasks.remove(N-1);
2596 }
2597 mRecentTasks.add(0, task);
2598 }
2599
2600 public void setRequestedOrientation(IBinder token,
2601 int requestedOrientation) {
2602 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002603 ActivityRecord r = mMainStack.isInStackLocked(token);
2604 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 return;
2606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002608 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002610 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002611 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 if (config != null) {
2613 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002614 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002615 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 }
2617 }
2618 Binder.restoreCallingIdentity(origId);
2619 }
2620 }
2621
2622 public int getRequestedOrientation(IBinder token) {
2623 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002624 ActivityRecord r = mMainStack.isInStackLocked(token);
2625 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2627 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002628 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 }
2630 }
2631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 /**
2633 * This is the internal entry point for handling Activity.finish().
2634 *
2635 * @param token The Binder token referencing the Activity we want to finish.
2636 * @param resultCode Result code, if any, from this Activity.
2637 * @param resultData Result data (Intent), if any, from this Activity.
2638 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002639 * @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 -08002640 */
2641 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2642 // Refuse possible leaked file descriptors
2643 if (resultData != null && resultData.hasFileDescriptors() == true) {
2644 throw new IllegalArgumentException("File descriptors passed in Intent");
2645 }
2646
2647 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002648 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002650 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 if (next != null) {
2652 // ask watcher if this is allowed
2653 boolean resumeOK = true;
2654 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002655 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002657 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 }
2659
2660 if (!resumeOK) {
2661 return false;
2662 }
2663 }
2664 }
2665 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002666 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 resultData, "app-request");
2668 Binder.restoreCallingIdentity(origId);
2669 return res;
2670 }
2671 }
2672
Dianne Hackborn860755f2010-06-03 18:47:52 -07002673 public final void finishHeavyWeightApp() {
2674 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2675 != PackageManager.PERMISSION_GRANTED) {
2676 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2677 + Binder.getCallingPid()
2678 + ", uid=" + Binder.getCallingUid()
2679 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2680 Slog.w(TAG, msg);
2681 throw new SecurityException(msg);
2682 }
2683
2684 synchronized(this) {
2685 if (mHeavyWeightProcess == null) {
2686 return;
2687 }
2688
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002689 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002690 mHeavyWeightProcess.activities);
2691 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002692 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002693 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002694 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002695 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002696 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002697 null, "finish-heavy");
2698 }
2699 }
2700 }
2701
2702 mHeavyWeightProcess = null;
2703 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2704 }
2705 }
2706
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002707 public void crashApplication(int uid, int initialPid, String packageName,
2708 String message) {
2709 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2710 != PackageManager.PERMISSION_GRANTED) {
2711 String msg = "Permission Denial: crashApplication() from pid="
2712 + Binder.getCallingPid()
2713 + ", uid=" + Binder.getCallingUid()
2714 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2715 Slog.w(TAG, msg);
2716 throw new SecurityException(msg);
2717 }
2718
2719 synchronized(this) {
2720 ProcessRecord proc = null;
2721
2722 // Figure out which process to kill. We don't trust that initialPid
2723 // still has any relation to current pids, so must scan through the
2724 // list.
2725 synchronized (mPidsSelfLocked) {
2726 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2727 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002728 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002729 continue;
2730 }
2731 if (p.pid == initialPid) {
2732 proc = p;
2733 break;
2734 }
2735 for (String str : p.pkgList) {
2736 if (str.equals(packageName)) {
2737 proc = p;
2738 }
2739 }
2740 }
2741 }
2742
2743 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002744 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002745 + " initialPid=" + initialPid
2746 + " packageName=" + packageName);
2747 return;
2748 }
2749
2750 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002751 if (proc.pid == Process.myPid()) {
2752 Log.w(TAG, "crashApplication: trying to crash self!");
2753 return;
2754 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002755 long ident = Binder.clearCallingIdentity();
2756 try {
2757 proc.thread.scheduleCrash(message);
2758 } catch (RemoteException e) {
2759 }
2760 Binder.restoreCallingIdentity(ident);
2761 }
2762 }
2763 }
2764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 public final void finishSubActivity(IBinder token, String resultWho,
2766 int requestCode) {
2767 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002769 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 Binder.restoreCallingIdentity(origId);
2771 }
2772 }
2773
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002774 public boolean finishActivityAffinity(IBinder token) {
2775 synchronized(this) {
2776 final long origId = Binder.clearCallingIdentity();
2777 boolean res = mMainStack.finishActivityAffinityLocked(token);
2778 Binder.restoreCallingIdentity(origId);
2779 return res;
2780 }
2781 }
2782
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002783 public boolean willActivityBeVisible(IBinder token) {
2784 synchronized(this) {
2785 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002786 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2787 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002788 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002789 return true;
2790 }
2791 if (r.fullscreen && !r.finishing) {
2792 return false;
2793 }
2794 }
2795 return true;
2796 }
2797 }
2798
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002799 public void overridePendingTransition(IBinder token, String packageName,
2800 int enterAnim, int exitAnim) {
2801 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002802 ActivityRecord self = mMainStack.isInStackLocked(token);
2803 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002804 return;
2805 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002806
2807 final long origId = Binder.clearCallingIdentity();
2808
2809 if (self.state == ActivityState.RESUMED
2810 || self.state == ActivityState.PAUSING) {
2811 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002812 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002813 }
2814
2815 Binder.restoreCallingIdentity(origId);
2816 }
2817 }
2818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 * Main function for removing an existing process from the activity manager
2821 * as a result of that process going away. Clears out all connections
2822 * to the process.
2823 */
2824 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002825 boolean restarting, boolean allowRestart) {
2826 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002828 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 }
2830
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002831 if (mProfileProc == app) {
2832 clearProfilerLocked();
2833 }
2834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002836 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2837 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2838 mMainStack.mPausingActivity = null;
2839 }
2840 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2841 mMainStack.mLastPausedActivity = null;
2842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843
2844 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002845 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846
2847 boolean atTop = true;
2848 boolean hasVisibleActivities = false;
2849
2850 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002851 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002852 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 TAG, "Removing app " + app + " from history with " + i + " entries");
2854 while (i > 0) {
2855 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002856 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002857 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002858 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2859 if (r.app == app) {
2860 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002861 if (ActivityStack.DEBUG_ADD_REMOVE) {
2862 RuntimeException here = new RuntimeException("here");
2863 here.fillInStackTrace();
2864 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2865 + ": haveState=" + r.haveState
2866 + " stateNotNeeded=" + r.stateNotNeeded
2867 + " finishing=" + r.finishing
2868 + " state=" + r.state, here);
2869 }
2870 if (!r.finishing) {
2871 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002872 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2873 System.identityHashCode(r),
2874 r.task.taskId, r.shortComponentName,
2875 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002876 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002877 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878
2879 } else {
2880 // We have the current state for this activity, so
2881 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002882 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 TAG, "Keeping entry, setting app to null");
2884 if (r.visible) {
2885 hasVisibleActivities = true;
2886 }
2887 r.app = null;
2888 r.nowVisible = false;
2889 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002890 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2891 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 r.icicle = null;
2893 }
2894 }
2895
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002896 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 }
2898 atTop = false;
2899 }
2900
2901 app.activities.clear();
2902
2903 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002904 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 + " running instrumentation " + app.instrumentationClass);
2906 Bundle info = new Bundle();
2907 info.putString("shortMsg", "Process crashed.");
2908 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2909 }
2910
2911 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002912 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 // If there was nothing to resume, and we are not already
2914 // restarting this process, but there is a visible activity that
2915 // is hosted by the process... then make sure all visible
2916 // activities are running, taking care of restarting this
2917 // process.
2918 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002919 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 }
2921 }
2922 }
2923 }
2924
2925 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2926 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002928 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2929 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2931 return i;
2932 }
2933 }
2934 return -1;
2935 }
2936
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002937 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002938 IApplicationThread thread) {
2939 if (thread == null) {
2940 return null;
2941 }
2942
2943 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002944 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 }
2946
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002947 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 IApplicationThread thread) {
2949
2950 mProcDeaths[0]++;
2951
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002952 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2953 synchronized (stats) {
2954 stats.noteProcessDiedLocked(app.info.uid, pid);
2955 }
2956
Magnus Edlund7bb25812010-02-24 15:45:06 +01002957 // Clean up already done if the process has been re-started.
2958 if (app.pid == pid && app.thread != null &&
2959 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002960 if (!app.killedBackground) {
2961 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2962 + ") has died.");
2963 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002964 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002965 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 TAG, "Dying app: " + app + ", pid: " + pid
2967 + ", thread: " + thread.asBinder());
2968 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002969 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970
2971 if (doLowMem) {
2972 // If there are no longer any background processes running,
2973 // and the app that died was not running instrumentation,
2974 // then tell everyone we are now low on memory.
2975 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002976 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2977 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002978 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 haveBg = true;
2980 break;
2981 }
2982 }
2983
2984 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002985 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002986 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002987 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2988 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002989 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002990 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2991 // The low memory report is overriding any current
2992 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002993 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002994 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002995 rec.lastRequestedGc = 0;
2996 } else {
2997 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002999 rec.reportLowMemory = true;
3000 rec.lastLowMemory = now;
3001 mProcessesToGc.remove(rec);
3002 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 }
3004 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003005 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003006 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007 }
3008 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003009 } else if (app.pid != pid) {
3010 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003011 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003012 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003013 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003014 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003015 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 + thread.asBinder());
3017 }
3018 }
3019
Dan Egnor42471dd2010-01-07 17:25:22 -08003020 /**
3021 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003022 * @param clearTraces causes the dump file to be erased prior to the new
3023 * traces being written, if true; when false, the new traces will be
3024 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003025 * @param firstPids of dalvik VM processes to dump stack traces for first
3026 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003027 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003028 * @return file containing stack traces, or null if no dump file is configured
3029 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003030 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003031 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003032 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3033 if (tracesPath == null || tracesPath.length() == 0) {
3034 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003036
3037 File tracesFile = new File(tracesPath);
3038 try {
3039 File tracesDir = tracesFile.getParentFile();
3040 if (!tracesDir.exists()) tracesFile.mkdirs();
3041 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3042
Christopher Tate6ee412d2010-05-28 12:01:56 -07003043 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003044 tracesFile.createNewFile();
3045 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3046 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003047 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003048 return null;
3049 }
3050
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003051 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003052 return tracesFile;
3053 }
3054
3055 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003056 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003057 // Use a FileObserver to detect when traces finish writing.
3058 // The order of traces is considered important to maintain for legibility.
3059 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3060 public synchronized void onEvent(int event, String path) { notify(); }
3061 };
3062
3063 try {
3064 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003065
3066 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003067 if (firstPids != null) {
3068 try {
3069 int num = firstPids.size();
3070 for (int i = 0; i < num; i++) {
3071 synchronized (observer) {
3072 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3073 observer.wait(200); // Wait for write-close, give up after 200msec
3074 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003075 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003076 } catch (InterruptedException e) {
3077 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003078 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003079 }
3080
3081 // Next measure CPU usage.
3082 if (processStats != null) {
3083 processStats.init();
3084 System.gc();
3085 processStats.update();
3086 try {
3087 synchronized (processStats) {
3088 processStats.wait(500); // measure over 1/2 second.
3089 }
3090 } catch (InterruptedException e) {
3091 }
3092 processStats.update();
3093
3094 // We'll take the stack crawls of just the top apps using CPU.
3095 final int N = processStats.countWorkingStats();
3096 int numProcs = 0;
3097 for (int i=0; i<N && numProcs<5; i++) {
3098 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3099 if (lastPids.indexOfKey(stats.pid) >= 0) {
3100 numProcs++;
3101 try {
3102 synchronized (observer) {
3103 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3104 observer.wait(200); // Wait for write-close, give up after 200msec
3105 }
3106 } catch (InterruptedException e) {
3107 Log.wtf(TAG, e);
3108 }
3109
3110 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003111 }
3112 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003113
Dan Egnor42471dd2010-01-07 17:25:22 -08003114 } finally {
3115 observer.stopWatching();
3116 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003117
3118 if (nativeProcs != null) {
3119 int[] pids = Process.getPidsForCommands(nativeProcs);
3120 if (pids != null) {
3121 for (int pid : pids) {
3122 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3123 }
3124 }
3125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 }
3127
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003128 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003129 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003130 return;
3131 }
3132 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3133 if (tracesPath == null || tracesPath.length() == 0) {
3134 return;
3135 }
3136
3137 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3138 StrictMode.allowThreadDiskWrites();
3139 try {
3140 final File tracesFile = new File(tracesPath);
3141 final File tracesDir = tracesFile.getParentFile();
3142 final File tracesTmp = new File(tracesDir, "__tmp__");
3143 try {
3144 if (!tracesDir.exists()) tracesFile.mkdirs();
3145 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3146
3147 if (tracesFile.exists()) {
3148 tracesTmp.delete();
3149 tracesFile.renameTo(tracesTmp);
3150 }
3151 StringBuilder sb = new StringBuilder();
3152 Time tobj = new Time();
3153 tobj.set(System.currentTimeMillis());
3154 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3155 sb.append(": ");
3156 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3157 sb.append(" since ");
3158 sb.append(msg);
3159 FileOutputStream fos = new FileOutputStream(tracesFile);
3160 fos.write(sb.toString().getBytes());
3161 if (app == null) {
3162 fos.write("\n*** No application process!".getBytes());
3163 }
3164 fos.close();
3165 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3166 } catch (IOException e) {
3167 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3168 return;
3169 }
3170
3171 if (app != null) {
3172 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3173 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003174 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003175 }
3176
3177 File lastTracesFile = null;
3178 File curTracesFile = null;
3179 for (int i=9; i>=0; i--) {
3180 String name = String.format("slow%02d.txt", i);
3181 curTracesFile = new File(tracesDir, name);
3182 if (curTracesFile.exists()) {
3183 if (lastTracesFile != null) {
3184 curTracesFile.renameTo(lastTracesFile);
3185 } else {
3186 curTracesFile.delete();
3187 }
3188 }
3189 lastTracesFile = curTracesFile;
3190 }
3191 tracesFile.renameTo(curTracesFile);
3192 if (tracesTmp.exists()) {
3193 tracesTmp.renameTo(tracesFile);
3194 }
3195 } finally {
3196 StrictMode.setThreadPolicy(oldPolicy);
3197 }
3198 }
3199
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003200 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3201 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003202 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3203 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3204
Dianne Hackborn287952c2010-09-22 22:34:31 -07003205 if (mController != null) {
3206 try {
3207 // 0 == continue, -1 = kill process immediately
3208 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3209 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3210 } catch (RemoteException e) {
3211 mController = null;
3212 }
3213 }
3214
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003215 long anrTime = SystemClock.uptimeMillis();
3216 if (MONITOR_CPU_USAGE) {
3217 updateCpuStatsNow();
3218 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003219
3220 synchronized (this) {
3221 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3222 if (mShuttingDown) {
3223 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3224 return;
3225 } else if (app.notResponding) {
3226 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3227 return;
3228 } else if (app.crashing) {
3229 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3230 return;
3231 }
3232
3233 // In case we come through here for the same app before completing
3234 // this one, mark as anring now so we will bail out.
3235 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003236
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003237 // Log the ANR to the event log.
3238 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3239 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003240
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003241 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003242 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003243
3244 int parentPid = app.pid;
3245 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003246 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003247
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003248 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003249
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003250 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3251 ProcessRecord r = mLruProcesses.get(i);
3252 if (r != null && r.thread != null) {
3253 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003254 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3255 if (r.persistent) {
3256 firstPids.add(pid);
3257 } else {
3258 lastPids.put(pid, Boolean.TRUE);
3259 }
3260 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 }
3263 }
3264
Dan Egnor42471dd2010-01-07 17:25:22 -08003265 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003266 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003267 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003268 info.append("ANR in ").append(app.processName);
3269 if (activity != null && activity.shortComponentName != null) {
3270 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003271 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003272 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003274 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003275 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003276 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003277 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279
Dianne Hackborn287952c2010-09-22 22:34:31 -07003280 final ProcessStats processStats = new ProcessStats(true);
3281
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003282 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003283
Dan Egnor42471dd2010-01-07 17:25:22 -08003284 String cpuInfo = null;
3285 if (MONITOR_CPU_USAGE) {
3286 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003287 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003288 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003289 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003290 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003291 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 }
3293
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003294 info.append(processStats.printCurrentState(anrTime));
3295
Joe Onorato8a9b2202010-02-26 18:56:32 -08003296 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003297 if (tracesFile == null) {
3298 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3299 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3300 }
3301
Jeff Sharkeya353d262011-10-28 11:12:06 -07003302 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3303 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003304
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003305 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003307 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3308 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003310 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3311 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 }
3313 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003314 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 }
3316 }
3317
Dan Egnor42471dd2010-01-07 17:25:22 -08003318 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3319 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3320 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003321
3322 synchronized (this) {
3323 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003324 Slog.w(TAG, "Killing " + app + ": background ANR");
3325 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3326 app.processName, app.setAdj, "background ANR");
3327 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003328 return;
3329 }
3330
3331 // Set the app's notResponding state, and look up the errorReportReceiver
3332 makeAppNotRespondingLocked(app,
3333 activity != null ? activity.shortComponentName : null,
3334 annotation != null ? "ANR " + annotation : "ANR",
3335 info.toString());
3336
3337 // Bring up the infamous App Not Responding dialog
3338 Message msg = Message.obtain();
3339 HashMap map = new HashMap();
3340 msg.what = SHOW_NOT_RESPONDING_MSG;
3341 msg.obj = map;
3342 map.put("app", app);
3343 if (activity != null) {
3344 map.put("activity", activity);
3345 }
3346
3347 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 }
3350
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003351 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3352 if (!mLaunchWarningShown) {
3353 mLaunchWarningShown = true;
3354 mHandler.post(new Runnable() {
3355 @Override
3356 public void run() {
3357 synchronized (ActivityManagerService.this) {
3358 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3359 d.show();
3360 mHandler.postDelayed(new Runnable() {
3361 @Override
3362 public void run() {
3363 synchronized (ActivityManagerService.this) {
3364 d.dismiss();
3365 mLaunchWarningShown = false;
3366 }
3367 }
3368 }, 4000);
3369 }
3370 }
3371 });
3372 }
3373 }
3374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003376 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003377 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 int uid = Binder.getCallingUid();
3379 int pid = Binder.getCallingPid();
3380 long callingId = Binder.clearCallingIdentity();
3381 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003382 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 int pkgUid = -1;
3384 synchronized(this) {
3385 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003386 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 } catch (RemoteException e) {
3388 }
3389 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003390 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003391 return false;
3392 }
3393 if (uid == pkgUid || checkComponentPermission(
3394 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003395 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003397 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 } else {
3399 throw new SecurityException(pid+" does not have permission:"+
3400 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3401 "for process:"+packageName);
3402 }
3403 }
3404
3405 try {
3406 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003407 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003408 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3409 Uri.fromParts("package", packageName, null));
3410 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003411 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003412 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 } catch (RemoteException e) {
3414 }
3415 } finally {
3416 Binder.restoreCallingIdentity(callingId);
3417 }
3418 return true;
3419 }
3420
Dianne Hackborn03abb812010-01-04 18:43:19 -08003421 public void killBackgroundProcesses(final String packageName) {
3422 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3423 != PackageManager.PERMISSION_GRANTED &&
3424 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3425 != PackageManager.PERMISSION_GRANTED) {
3426 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 + Binder.getCallingPid()
3428 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003429 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003430 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 throw new SecurityException(msg);
3432 }
3433
Amith Yamasani483f3b02012-03-13 16:08:00 -07003434 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 long callingId = Binder.clearCallingIdentity();
3436 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003437 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 int pkgUid = -1;
3439 synchronized(this) {
3440 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003441 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 } catch (RemoteException e) {
3443 }
3444 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003445 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 return;
3447 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003448 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003449 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3450 }
3451 } finally {
3452 Binder.restoreCallingIdentity(callingId);
3453 }
3454 }
3455
3456 public void killAllBackgroundProcesses() {
3457 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3458 != PackageManager.PERMISSION_GRANTED) {
3459 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3460 + Binder.getCallingPid()
3461 + ", uid=" + Binder.getCallingUid()
3462 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3463 Slog.w(TAG, msg);
3464 throw new SecurityException(msg);
3465 }
3466
3467 long callingId = Binder.clearCallingIdentity();
3468 try {
3469 synchronized(this) {
3470 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3471 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3472 final int NA = apps.size();
3473 for (int ia=0; ia<NA; ia++) {
3474 ProcessRecord app = apps.valueAt(ia);
3475 if (app.persistent) {
3476 // we don't kill persistent processes
3477 continue;
3478 }
3479 if (app.removed) {
3480 procs.add(app);
3481 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3482 app.removed = true;
3483 procs.add(app);
3484 }
3485 }
3486 }
3487
3488 int N = procs.size();
3489 for (int i=0; i<N; i++) {
3490 removeProcessLocked(procs.get(i), false, true, "kill all background");
3491 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003492 }
3493 } finally {
3494 Binder.restoreCallingIdentity(callingId);
3495 }
3496 }
3497
3498 public void forceStopPackage(final String packageName) {
3499 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3500 != PackageManager.PERMISSION_GRANTED) {
3501 String msg = "Permission Denial: forceStopPackage() from pid="
3502 + Binder.getCallingPid()
3503 + ", uid=" + Binder.getCallingUid()
3504 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003505 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003506 throw new SecurityException(msg);
3507 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003508 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003509 long callingId = Binder.clearCallingIdentity();
3510 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003511 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003512 int pkgUid = -1;
3513 synchronized(this) {
3514 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003515 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003516 } catch (RemoteException e) {
3517 }
3518 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003519 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003520 return;
3521 }
3522 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003523 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003524 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003525 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003526 } catch (IllegalArgumentException e) {
3527 Slog.w(TAG, "Failed trying to unstop package "
3528 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 }
3531 } finally {
3532 Binder.restoreCallingIdentity(callingId);
3533 }
3534 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003535
3536 /*
3537 * The pkg name and uid have to be specified.
3538 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3539 */
3540 public void killApplicationWithUid(String pkg, int uid) {
3541 if (pkg == null) {
3542 return;
3543 }
3544 // Make sure the uid is valid.
3545 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003546 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003547 return;
3548 }
3549 int callerUid = Binder.getCallingUid();
3550 // Only the system server can kill an application
3551 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003552 // Post an aysnc message to kill the application
3553 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3554 msg.arg1 = uid;
3555 msg.arg2 = 0;
3556 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003557 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003558 } else {
3559 throw new SecurityException(callerUid + " cannot kill pkg: " +
3560 pkg);
3561 }
3562 }
3563
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003564 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003565 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003566
3567 final int uid = Binder.getCallingUid();
3568 final long origId = Binder.clearCallingIdentity();
3569 synchronized (this) {
3570 closeSystemDialogsLocked(uid, reason);
3571 }
3572 Binder.restoreCallingIdentity(origId);
3573 }
3574
3575 void closeSystemDialogsLocked(int callingUid, String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003576 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003577 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003578 if (reason != null) {
3579 intent.putExtra("reason", reason);
3580 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003581 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003582
Dianne Hackborne302a162012-05-15 14:58:32 -07003583 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3584 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003585 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003586 r.stack.finishActivityLocked(r, i,
3587 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003588 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003589 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003590
3591 broadcastIntentLocked(null, null, intent, null,
3592 null, 0, null, null, null, false, false, -1,
3593 callingUid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003594 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003595
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003596 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003597 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003598 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003599 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3600 for (int i=pids.length-1; i>=0; i--) {
3601 infos[i] = new Debug.MemoryInfo();
3602 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003603 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003604 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003605 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003606
Dianne Hackbornb437e092011-08-05 17:50:29 -07003607 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003608 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003609 long[] pss = new long[pids.length];
3610 for (int i=pids.length-1; i>=0; i--) {
3611 pss[i] = Debug.getPss(pids[i]);
3612 }
3613 return pss;
3614 }
3615
Christopher Tate5e1ab332009-09-01 20:32:49 -07003616 public void killApplicationProcess(String processName, int uid) {
3617 if (processName == null) {
3618 return;
3619 }
3620
3621 int callerUid = Binder.getCallingUid();
3622 // Only the system server can kill an application
3623 if (callerUid == Process.SYSTEM_UID) {
3624 synchronized (this) {
3625 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003626 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003627 try {
3628 app.thread.scheduleSuicide();
3629 } catch (RemoteException e) {
3630 // If the other end already died, then our work here is done.
3631 }
3632 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003633 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003634 + processName + " / " + uid);
3635 }
3636 }
3637 } else {
3638 throw new SecurityException(callerUid + " cannot kill app process: " +
3639 processName);
3640 }
3641 }
3642
Dianne Hackborn03abb812010-01-04 18:43:19 -08003643 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003644 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3646 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003647 if (!mProcessesReady) {
3648 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 intent.putExtra(Intent.EXTRA_UID, uid);
3651 broadcastIntentLocked(null, null, intent,
3652 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003653 false, false,
3654 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 }
3656
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003657 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003658 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003659 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003660 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661
Dianne Hackborn03abb812010-01-04 18:43:19 -08003662 // Remove all processes this package may have touched: all with the
3663 // same UID (except for the system or root user), and all whose name
3664 // matches the package name.
3665 final String procNamePrefix = packageName + ":";
3666 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3667 final int NA = apps.size();
3668 for (int ia=0; ia<NA; ia++) {
3669 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003670 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003671 // we don't kill persistent processes
3672 continue;
3673 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003674 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003675 if (doit) {
3676 procs.add(app);
3677 }
Amith Yamasani13593602012-03-22 16:16:17 -07003678 // If uid is specified and the uid and process name match
3679 // Or, the uid is not specified and the process name matches
3680 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003681 || ((app.processName.equals(packageName)
3682 || app.processName.startsWith(procNamePrefix))
3683 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003684 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003685 if (!doit) {
3686 return true;
3687 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003688 app.removed = true;
3689 procs.add(app);
3690 }
3691 }
3692 }
3693 }
3694
3695 int N = procs.size();
3696 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003697 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003698 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003699 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003700 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003701
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003702 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003703 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003704 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003705 int i;
3706 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 if (uid < 0) {
3709 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003710 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003711 } catch (RemoteException e) {
3712 }
3713 }
3714
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003715 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003716 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003717
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003718 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3719 while (badApps.hasNext()) {
3720 SparseArray<Long> ba = badApps.next();
3721 if (ba.get(uid) != null) {
3722 badApps.remove();
3723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 }
3725 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003726
3727 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003728 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003730 TaskRecord lastTask = null;
3731 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003732 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003733 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003734 if (r.userId == userId
3735 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003736 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003737 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003738 if (r.finishing) {
3739 // If this activity is just finishing, then it is not
3740 // interesting as far as something to stop.
3741 continue;
3742 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003743 return true;
3744 }
3745 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003746 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003747 if (samePackage) {
3748 if (r.app != null) {
3749 r.app.removed = true;
3750 }
3751 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003753 lastTask = r.task;
3754 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003755 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003756 i--;
3757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 }
3759 }
3760
3761 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003762 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003763 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003764 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003765 if (!doit) {
3766 return true;
3767 }
3768 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003769 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 if (service.app != null) {
3771 service.app.removed = true;
3772 }
3773 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003774 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775 services.add(service);
3776 }
3777 }
3778
3779 N = services.size();
3780 for (i=0; i<N; i++) {
3781 bringDownServiceLocked(services.get(i), true);
3782 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003783
3784 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003785 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003786 if (provider.info.packageName.equals(name)
3787 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3788 if (!doit) {
3789 return true;
3790 }
3791 didSomething = true;
3792 providers.add(provider);
3793 }
3794 }
3795
3796 N = providers.size();
3797 for (i=0; i<N; i++) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003798 removeDyingProviderLocked(null, providers.get(i), true);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003799 }
3800
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003801 if (doit) {
3802 if (purgeCache) {
3803 AttributeCache ac = AttributeCache.instance();
3804 if (ac != null) {
3805 ac.removePackage(name);
3806 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003807 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003808 if (mBooted) {
3809 mMainStack.resumeTopActivityLocked(null);
3810 mMainStack.scheduleIdleLocked();
3811 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003812 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003813
3814 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 }
3816
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003817 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003818 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003819 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003820 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003821 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003822 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 + "/" + uid + ")");
3824
3825 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003826 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003827 if (mHeavyWeightProcess == app) {
3828 mHeavyWeightProcess = null;
3829 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831 boolean needRestart = false;
3832 if (app.pid > 0 && app.pid != MY_PID) {
3833 int pid = app.pid;
3834 synchronized (mPidsSelfLocked) {
3835 mPidsSelfLocked.remove(pid);
3836 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3837 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003838 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003839 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003840 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003841 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003843 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003845 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 } else {
3847 needRestart = true;
3848 }
3849 }
3850 } else {
3851 mRemovedProcesses.add(app);
3852 }
3853
3854 return needRestart;
3855 }
3856
3857 private final void processStartTimedOutLocked(ProcessRecord app) {
3858 final int pid = app.pid;
3859 boolean gone = false;
3860 synchronized (mPidsSelfLocked) {
3861 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3862 if (knownApp != null && knownApp.thread == null) {
3863 mPidsSelfLocked.remove(pid);
3864 gone = true;
3865 }
3866 }
3867
3868 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003869 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003870 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003871 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003872 mProcessNames.remove(app.processName, app.uid);
3873 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003874 if (mHeavyWeightProcess == app) {
3875 mHeavyWeightProcess = null;
3876 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3877 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003878 // Take care of any launching providers waiting for this process.
3879 checkAppInLaunchingProvidersLocked(app, true);
3880 // Take care of any services that are waiting for the process.
3881 for (int i=0; i<mPendingServices.size(); i++) {
3882 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003883 if ((app.uid == sr.appInfo.uid
3884 && app.processName.equals(sr.processName))
3885 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003886 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003887 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003888 mPendingServices.remove(i);
3889 i--;
3890 bringDownServiceLocked(sr, true);
3891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003893 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3894 app.processName, app.setAdj, "start timeout");
3895 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003896 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003897 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003898 try {
3899 IBackupManager bm = IBackupManager.Stub.asInterface(
3900 ServiceManager.getService(Context.BACKUP_SERVICE));
3901 bm.agentDisconnected(app.info.packageName);
3902 } catch (RemoteException e) {
3903 // Can't happen; the backup manager is local
3904 }
3905 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003906 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003907 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003908 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003911 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 }
3913 }
3914
3915 private final boolean attachApplicationLocked(IApplicationThread thread,
3916 int pid) {
3917
3918 // Find the application record that is being attached... either via
3919 // the pid if we are running in multiple processes, or just pull the
3920 // next app record if we are emulating process with anonymous threads.
3921 ProcessRecord app;
3922 if (pid != MY_PID && pid >= 0) {
3923 synchronized (mPidsSelfLocked) {
3924 app = mPidsSelfLocked.get(pid);
3925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 } else {
3927 app = null;
3928 }
3929
3930 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003931 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003933 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003935 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 } else {
3937 try {
3938 thread.scheduleExit();
3939 } catch (Exception e) {
3940 // Ignore exceptions.
3941 }
3942 }
3943 return false;
3944 }
3945
3946 // If this application record is still attached to a previous
3947 // process, clean it up now.
3948 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003949 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 }
3951
3952 // Tell the process all about itself.
3953
Joe Onorato8a9b2202010-02-26 18:56:32 -08003954 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 TAG, "Binding process pid " + pid + " to record " + app);
3956
3957 String processName = app.processName;
3958 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003959 AppDeathRecipient adr = new AppDeathRecipient(
3960 app, pid, thread);
3961 thread.asBinder().linkToDeath(adr, 0);
3962 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 } catch (RemoteException e) {
3964 app.resetPackageList();
3965 startProcessLocked(app, "link fail", processName);
3966 return false;
3967 }
3968
Doug Zongker2bec3d42009-12-04 12:52:44 -08003969 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970
3971 app.thread = thread;
3972 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003973 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3974 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 app.forcingToForeground = null;
3976 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003977 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 app.debugging = false;
3979
3980 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3981
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003982 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003983 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003985 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003986 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003987 }
3988
Joe Onorato8a9b2202010-02-26 18:56:32 -08003989 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 TAG, "New app record " + app
3991 + " thread=" + thread.asBinder() + " pid=" + pid);
3992 try {
3993 int testMode = IApplicationThread.DEBUG_OFF;
3994 if (mDebugApp != null && mDebugApp.equals(processName)) {
3995 testMode = mWaitForDebugger
3996 ? IApplicationThread.DEBUG_WAIT
3997 : IApplicationThread.DEBUG_ON;
3998 app.debugging = true;
3999 if (mDebugTransient) {
4000 mDebugApp = mOrigDebugApp;
4001 mWaitForDebugger = mOrigWaitForDebugger;
4002 }
4003 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004004 String profileFile = app.instrumentationProfileFile;
4005 ParcelFileDescriptor profileFd = null;
4006 boolean profileAutoStop = false;
4007 if (mProfileApp != null && mProfileApp.equals(processName)) {
4008 mProfileProc = app;
4009 profileFile = mProfileFile;
4010 profileFd = mProfileFd;
4011 profileAutoStop = mAutoStopProfiler;
4012 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004013 boolean enableOpenGlTrace = false;
4014 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4015 enableOpenGlTrace = true;
4016 mOpenGlTraceApp = null;
4017 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004018
Christopher Tate181fafa2009-05-14 11:12:14 -07004019 // If the app is being launched for restore or full backup, set it up specially
4020 boolean isRestrictedBackupMode = false;
4021 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4022 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004023 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004024 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4025 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004026
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004027 ensurePackageDexOpt(app.instrumentationInfo != null
4028 ? app.instrumentationInfo.packageName
4029 : app.info.packageName);
4030 if (app.instrumentationClass != null) {
4031 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004032 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004033 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004034 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004035 ApplicationInfo appInfo = app.instrumentationInfo != null
4036 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004037 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004038 if (profileFd != null) {
4039 profileFd = profileFd.dup();
4040 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004041 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004042 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004043 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4044 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004045 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004046 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004047 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004048 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 } catch (Exception e) {
4050 // todo: Yikes! What should we do? For now we will try to
4051 // start another process, but that could easily get us in
4052 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004053 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054
4055 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004056 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 startProcessLocked(app, "bind fail", processName);
4058 return false;
4059 }
4060
4061 // Remove this record from the list of starting applications.
4062 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004063 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4064 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 mProcessesOnHold.remove(app);
4066
4067 boolean badApp = false;
4068 boolean didSomething = false;
4069
4070 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004071 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004072 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004073 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 && processName.equals(hr.processName)) {
4075 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004076 if (mHeadless) {
4077 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4078 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079 didSomething = true;
4080 }
4081 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004082 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 + hr.intent.getComponent().flattenToShortString(), e);
4084 badApp = true;
4085 }
4086 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004087 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 }
4089 }
4090
4091 // Find any services that should be running in this process...
4092 if (!badApp && mPendingServices.size() > 0) {
4093 ServiceRecord sr = null;
4094 try {
4095 for (int i=0; i<mPendingServices.size(); i++) {
4096 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004097 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4098 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 continue;
4100 }
4101
4102 mPendingServices.remove(i);
4103 i--;
4104 realStartServiceLocked(sr, app);
4105 didSomething = true;
4106 }
4107 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004108 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 + sr.shortName, e);
4110 badApp = true;
4111 }
4112 }
4113
Christopher Tatef46723b2012-01-26 14:19:24 -08004114 // Check if a next-broadcast receiver is in this process...
4115 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004117 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004118 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004119 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 }
4122 }
4123
Christopher Tate181fafa2009-05-14 11:12:14 -07004124 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004125 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004126 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004127 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004128 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004129 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4130 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4131 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004132 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004133 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004134 e.printStackTrace();
4135 }
4136 }
4137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 if (badApp) {
4139 // todo: Also need to kill application to deal with all
4140 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004141 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004142 return false;
4143 }
4144
4145 if (!didSomething) {
4146 updateOomAdjLocked();
4147 }
4148
4149 return true;
4150 }
4151
4152 public final void attachApplication(IApplicationThread thread) {
4153 synchronized (this) {
4154 int callingPid = Binder.getCallingPid();
4155 final long origId = Binder.clearCallingIdentity();
4156 attachApplicationLocked(thread, callingPid);
4157 Binder.restoreCallingIdentity(origId);
4158 }
4159 }
4160
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004161 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004163 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4164 if (stopProfiling) {
4165 synchronized (this) {
4166 if (mProfileProc == r.app) {
4167 if (mProfileFd != null) {
4168 try {
4169 mProfileFd.close();
4170 } catch (IOException e) {
4171 }
4172 clearProfilerLocked();
4173 }
4174 }
4175 }
4176 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177 Binder.restoreCallingIdentity(origId);
4178 }
4179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004181 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004182 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004184
4185 synchronized (this) {
4186 updateEventDispatchingLocked();
4187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188 }
4189
Dianne Hackborn661cd522011-08-22 00:26:20 -07004190 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004191 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004192 mWindowManager.showBootMessage(msg, always);
4193 }
4194
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004195 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004196 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004197 final long token = Binder.clearCallingIdentity();
4198 try {
4199 synchronized (this) {
4200 if (mLockScreenShown) {
4201 mLockScreenShown = false;
4202 comeOutOfSleepIfNeededLocked();
4203 }
4204 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004205 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004206 } finally {
4207 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004208 }
4209 }
4210
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004211 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004212 IntentFilter pkgFilter = new IntentFilter();
4213 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4214 pkgFilter.addDataScheme("package");
4215 mContext.registerReceiver(new BroadcastReceiver() {
4216 @Override
4217 public void onReceive(Context context, Intent intent) {
4218 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4219 if (pkgs != null) {
4220 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004221 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004222 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4223 setResultCode(Activity.RESULT_OK);
4224 return;
4225 }
4226 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004227 }
4228 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004229 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004230 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004231
4232 IntentFilter userFilter = new IntentFilter();
4233 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4234 mContext.registerReceiver(new BroadcastReceiver() {
4235 @Override
4236 public void onReceive(Context context, Intent intent) {
4237 onUserRemoved(intent);
4238 }
4239 }, userFilter);
4240
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004241 synchronized (this) {
4242 // Ensure that any processes we had put on hold are now started
4243 // up.
4244 final int NP = mProcessesOnHold.size();
4245 if (NP > 0) {
4246 ArrayList<ProcessRecord> procs =
4247 new ArrayList<ProcessRecord>(mProcessesOnHold);
4248 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004249 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4250 + procs.get(ip));
4251 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004252 }
4253 }
4254
4255 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004256 // Start looking for apps that are abusing wake locks.
4257 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004258 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004259 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004260 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004261 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004262 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004263 broadcastIntentLocked(null, null,
4264 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4265 null, null, 0, null, null,
4266 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004267 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004268 }
4269 }
4270 }
4271
4272 final void ensureBootCompleted() {
4273 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004274 boolean enableScreen;
4275 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004276 booting = mBooting;
4277 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004278 enableScreen = !mBooted;
4279 mBooted = true;
4280 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004281
4282 if (booting) {
4283 finishBooting();
4284 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004285
4286 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004287 enableScreenAfterBoot();
4288 }
4289 }
4290
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004291 public final void activityPaused(IBinder token) {
4292 final long origId = Binder.clearCallingIdentity();
4293 mMainStack.activityPaused(token, false);
4294 Binder.restoreCallingIdentity(origId);
4295 }
4296
4297 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4298 CharSequence description) {
4299 if (localLOGV) Slog.v(
4300 TAG, "Activity stopped: token=" + token);
4301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 // Refuse possible leaked file descriptors
4303 if (icicle != null && icicle.hasFileDescriptors()) {
4304 throw new IllegalArgumentException("File descriptors passed in Bundle");
4305 }
4306
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004307 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308
4309 final long origId = Binder.clearCallingIdentity();
4310
4311 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004312 r = mMainStack.isInStackLocked(token);
4313 if (r != null) {
4314 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315 }
4316 }
4317
4318 if (r != null) {
4319 sendPendingThumbnail(r, null, null, null, false);
4320 }
4321
4322 trimApplications();
4323
4324 Binder.restoreCallingIdentity(origId);
4325 }
4326
4327 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004328 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004329 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 }
4331
4332 public String getCallingPackage(IBinder token) {
4333 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004334 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004335 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 }
4337 }
4338
4339 public ComponentName getCallingActivity(IBinder token) {
4340 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004341 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004342 return r != null ? r.intent.getComponent() : null;
4343 }
4344 }
4345
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004346 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004347 ActivityRecord r = mMainStack.isInStackLocked(token);
4348 if (r == null) {
4349 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004350 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004351 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004352 }
4353
4354 public ComponentName getActivityClassForToken(IBinder token) {
4355 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004356 ActivityRecord r = mMainStack.isInStackLocked(token);
4357 if (r == null) {
4358 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004359 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004360 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361 }
4362 }
4363
4364 public String getPackageForToken(IBinder token) {
4365 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004366 ActivityRecord r = mMainStack.isInStackLocked(token);
4367 if (r == null) {
4368 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004369 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004370 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 }
4372 }
4373
4374 public IIntentSender getIntentSender(int type,
4375 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004376 int requestCode, Intent[] intents, String[] resolvedTypes,
4377 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004378 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004380 if (intents != null) {
4381 if (intents.length < 1) {
4382 throw new IllegalArgumentException("Intents array length must be >= 1");
4383 }
4384 for (int i=0; i<intents.length; i++) {
4385 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004386 if (intent != null) {
4387 if (intent.hasFileDescriptors()) {
4388 throw new IllegalArgumentException("File descriptors passed in Intent");
4389 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004390 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004391 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4392 throw new IllegalArgumentException(
4393 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4394 }
4395 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004396 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004397 }
4398 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004399 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004400 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004401 }
4402 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004403 if (options != null) {
4404 if (options.hasFileDescriptors()) {
4405 throw new IllegalArgumentException("File descriptors passed in options");
4406 }
4407 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409 synchronized(this) {
4410 int callingUid = Binder.getCallingUid();
4411 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004412 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004413 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004414 .getPackageUid(packageName, UserId.getUserId(callingUid));
4415 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004416 String msg = "Permission Denial: getIntentSender() from pid="
4417 + Binder.getCallingPid()
4418 + ", uid=" + Binder.getCallingUid()
4419 + ", (need uid=" + uid + ")"
4420 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004421 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 throw new SecurityException(msg);
4423 }
4424 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004425
Amith Yamasani742a6712011-05-04 14:49:28 -07004426 if (DEBUG_MU)
4427 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4428 + Binder.getOrigCallingUid());
4429 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004430 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 } catch (RemoteException e) {
4433 throw new SecurityException(e);
4434 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004435 }
4436 }
4437
4438 IIntentSender getIntentSenderLocked(int type,
4439 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004440 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4441 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004442 if (DEBUG_MU)
4443 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004444 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004445 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004446 activity = mMainStack.isInStackLocked(token);
4447 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004448 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004449 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004450 if (activity.finishing) {
4451 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004453 }
4454
4455 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4456 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4457 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4458 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4459 |PendingIntent.FLAG_UPDATE_CURRENT);
4460
4461 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4462 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004463 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004464 WeakReference<PendingIntentRecord> ref;
4465 ref = mIntentSenderRecords.get(key);
4466 PendingIntentRecord rec = ref != null ? ref.get() : null;
4467 if (rec != null) {
4468 if (!cancelCurrent) {
4469 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004470 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004471 rec.key.requestIntent.replaceExtras(intents != null ?
4472 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004473 }
4474 if (intents != null) {
4475 intents[intents.length-1] = rec.key.requestIntent;
4476 rec.key.allIntents = intents;
4477 rec.key.allResolvedTypes = resolvedTypes;
4478 } else {
4479 rec.key.allIntents = null;
4480 rec.key.allResolvedTypes = null;
4481 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004483 return rec;
4484 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004485 rec.canceled = true;
4486 mIntentSenderRecords.remove(key);
4487 }
4488 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 return rec;
4490 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004491 rec = new PendingIntentRecord(this, key, callingUid);
4492 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004493 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004494 if (activity.pendingResults == null) {
4495 activity.pendingResults
4496 = new HashSet<WeakReference<PendingIntentRecord>>();
4497 }
4498 activity.pendingResults.add(rec.ref);
4499 }
4500 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 }
4502
4503 public void cancelIntentSender(IIntentSender sender) {
4504 if (!(sender instanceof PendingIntentRecord)) {
4505 return;
4506 }
4507 synchronized(this) {
4508 PendingIntentRecord rec = (PendingIntentRecord)sender;
4509 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004510 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004511 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004512 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 String msg = "Permission Denial: cancelIntentSender() from pid="
4514 + Binder.getCallingPid()
4515 + ", uid=" + Binder.getCallingUid()
4516 + " is not allowed to cancel packges "
4517 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004518 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004519 throw new SecurityException(msg);
4520 }
4521 } catch (RemoteException e) {
4522 throw new SecurityException(e);
4523 }
4524 cancelIntentSenderLocked(rec, true);
4525 }
4526 }
4527
4528 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4529 rec.canceled = true;
4530 mIntentSenderRecords.remove(rec.key);
4531 if (cleanActivity && rec.key.activity != null) {
4532 rec.key.activity.pendingResults.remove(rec.ref);
4533 }
4534 }
4535
4536 public String getPackageForIntentSender(IIntentSender pendingResult) {
4537 if (!(pendingResult instanceof PendingIntentRecord)) {
4538 return null;
4539 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004540 try {
4541 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4542 return res.key.packageName;
4543 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 }
4545 return null;
4546 }
4547
Christopher Tatec4a07d12012-04-06 14:19:13 -07004548 public int getUidForIntentSender(IIntentSender sender) {
4549 if (sender instanceof PendingIntentRecord) {
4550 try {
4551 PendingIntentRecord res = (PendingIntentRecord)sender;
4552 return res.uid;
4553 } catch (ClassCastException e) {
4554 }
4555 }
4556 return -1;
4557 }
4558
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004559 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4560 if (!(pendingResult instanceof PendingIntentRecord)) {
4561 return false;
4562 }
4563 try {
4564 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4565 if (res.key.allIntents == null) {
4566 return false;
4567 }
4568 for (int i=0; i<res.key.allIntents.length; i++) {
4569 Intent intent = res.key.allIntents[i];
4570 if (intent.getPackage() != null && intent.getComponent() != null) {
4571 return false;
4572 }
4573 }
4574 return true;
4575 } catch (ClassCastException e) {
4576 }
4577 return false;
4578 }
4579
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004580 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4581 if (!(pendingResult instanceof PendingIntentRecord)) {
4582 return false;
4583 }
4584 try {
4585 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4586 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4587 return true;
4588 }
4589 return false;
4590 } catch (ClassCastException e) {
4591 }
4592 return false;
4593 }
4594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004595 public void setProcessLimit(int max) {
4596 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4597 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004598 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004599 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004600 mProcessLimitOverride = max;
4601 }
4602 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004603 }
4604
4605 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004606 synchronized (this) {
4607 return mProcessLimitOverride;
4608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004609 }
4610
4611 void foregroundTokenDied(ForegroundToken token) {
4612 synchronized (ActivityManagerService.this) {
4613 synchronized (mPidsSelfLocked) {
4614 ForegroundToken cur
4615 = mForegroundProcesses.get(token.pid);
4616 if (cur != token) {
4617 return;
4618 }
4619 mForegroundProcesses.remove(token.pid);
4620 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4621 if (pr == null) {
4622 return;
4623 }
4624 pr.forcingToForeground = null;
4625 pr.foregroundServices = false;
4626 }
4627 updateOomAdjLocked();
4628 }
4629 }
4630
4631 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4632 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4633 "setProcessForeground()");
4634 synchronized(this) {
4635 boolean changed = false;
4636
4637 synchronized (mPidsSelfLocked) {
4638 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004639 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004640 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 return;
4642 }
4643 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4644 if (oldToken != null) {
4645 oldToken.token.unlinkToDeath(oldToken, 0);
4646 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004647 if (pr != null) {
4648 pr.forcingToForeground = null;
4649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004650 changed = true;
4651 }
4652 if (isForeground && token != null) {
4653 ForegroundToken newToken = new ForegroundToken() {
4654 public void binderDied() {
4655 foregroundTokenDied(this);
4656 }
4657 };
4658 newToken.pid = pid;
4659 newToken.token = token;
4660 try {
4661 token.linkToDeath(newToken, 0);
4662 mForegroundProcesses.put(pid, newToken);
4663 pr.forcingToForeground = token;
4664 changed = true;
4665 } catch (RemoteException e) {
4666 // If the process died while doing this, we will later
4667 // do the cleanup with the process death link.
4668 }
4669 }
4670 }
4671
4672 if (changed) {
4673 updateOomAdjLocked();
4674 }
4675 }
4676 }
4677
4678 // =========================================================
4679 // PERMISSIONS
4680 // =========================================================
4681
4682 static class PermissionController extends IPermissionController.Stub {
4683 ActivityManagerService mActivityManagerService;
4684 PermissionController(ActivityManagerService activityManagerService) {
4685 mActivityManagerService = activityManagerService;
4686 }
4687
4688 public boolean checkPermission(String permission, int pid, int uid) {
4689 return mActivityManagerService.checkPermission(permission, pid,
4690 uid) == PackageManager.PERMISSION_GRANTED;
4691 }
4692 }
4693
4694 /**
4695 * This can be called with or without the global lock held.
4696 */
4697 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004698 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004699 // We might be performing an operation on behalf of an indirect binder
4700 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4701 // client identity accordingly before proceeding.
4702 Identity tlsIdentity = sCallerIdentity.get();
4703 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004704 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4706 uid = tlsIdentity.uid;
4707 pid = tlsIdentity.pid;
4708 }
4709
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004710 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004711 return PackageManager.PERMISSION_GRANTED;
4712 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004713
4714 return ActivityManager.checkComponentPermission(permission, uid,
4715 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004716 }
4717
4718 /**
4719 * As the only public entry point for permissions checking, this method
4720 * can enforce the semantic that requesting a check on a null global
4721 * permission is automatically denied. (Internally a null permission
4722 * string is used when calling {@link #checkComponentPermission} in cases
4723 * when only uid-based security is needed.)
4724 *
4725 * This can be called with or without the global lock held.
4726 */
4727 public int checkPermission(String permission, int pid, int uid) {
4728 if (permission == null) {
4729 return PackageManager.PERMISSION_DENIED;
4730 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004731 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004732 }
4733
4734 /**
4735 * Binder IPC calls go through the public entry point.
4736 * This can be called with or without the global lock held.
4737 */
4738 int checkCallingPermission(String permission) {
4739 return checkPermission(permission,
4740 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004741 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742 }
4743
4744 /**
4745 * This can be called with or without the global lock held.
4746 */
4747 void enforceCallingPermission(String permission, String func) {
4748 if (checkCallingPermission(permission)
4749 == PackageManager.PERMISSION_GRANTED) {
4750 return;
4751 }
4752
4753 String msg = "Permission Denial: " + func + " from pid="
4754 + Binder.getCallingPid()
4755 + ", uid=" + Binder.getCallingUid()
4756 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004757 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004758 throw new SecurityException(msg);
4759 }
4760
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004761 /**
4762 * Determine if UID is holding permissions required to access {@link Uri} in
4763 * the given {@link ProviderInfo}. Final permission checking is always done
4764 * in {@link ContentProvider}.
4765 */
4766 private final boolean checkHoldingPermissionsLocked(
4767 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004768 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4769 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004770
4771 if (pi.applicationInfo.uid == uid) {
4772 return true;
4773 } else if (!pi.exported) {
4774 return false;
4775 }
4776
4777 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4778 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004779 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004780 // check if target holds top-level <provider> permissions
4781 if (!readMet && pi.readPermission != null
4782 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4783 readMet = true;
4784 }
4785 if (!writeMet && pi.writePermission != null
4786 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4787 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004788 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004789
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004790 // track if unprotected read/write is allowed; any denied
4791 // <path-permission> below removes this ability
4792 boolean allowDefaultRead = pi.readPermission == null;
4793 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004794
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004795 // check if target holds any <path-permission> that match uri
4796 final PathPermission[] pps = pi.pathPermissions;
4797 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004798 final String path = uri.getPath();
4799 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004800 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004801 i--;
4802 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004803 if (pp.match(path)) {
4804 if (!readMet) {
4805 final String pprperm = pp.getReadPermission();
4806 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4807 + pprperm + " for " + pp.getPath()
4808 + ": match=" + pp.match(path)
4809 + " check=" + pm.checkUidPermission(pprperm, uid));
4810 if (pprperm != null) {
4811 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4812 readMet = true;
4813 } else {
4814 allowDefaultRead = false;
4815 }
4816 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004817 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004818 if (!writeMet) {
4819 final String ppwperm = pp.getWritePermission();
4820 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4821 + ppwperm + " for " + pp.getPath()
4822 + ": match=" + pp.match(path)
4823 + " check=" + pm.checkUidPermission(ppwperm, uid));
4824 if (ppwperm != null) {
4825 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4826 writeMet = true;
4827 } else {
4828 allowDefaultWrite = false;
4829 }
4830 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004831 }
4832 }
4833 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004834 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004835
4836 // grant unprotected <provider> read/write, if not blocked by
4837 // <path-permission> above
4838 if (allowDefaultRead) readMet = true;
4839 if (allowDefaultWrite) writeMet = true;
4840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004841 } catch (RemoteException e) {
4842 return false;
4843 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004844
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004845 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004846 }
4847
4848 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4849 int modeFlags) {
4850 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004851 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004852 return true;
4853 }
4854 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4855 if (perms == null) return false;
4856 UriPermission perm = perms.get(uri);
4857 if (perm == null) return false;
4858 return (modeFlags&perm.modeFlags) == modeFlags;
4859 }
4860
4861 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004862 enforceNotIsolatedCaller("checkUriPermission");
4863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004864 // Another redirected-binder-call permissions check as in
4865 // {@link checkComponentPermission}.
4866 Identity tlsIdentity = sCallerIdentity.get();
4867 if (tlsIdentity != null) {
4868 uid = tlsIdentity.uid;
4869 pid = tlsIdentity.pid;
4870 }
4871
Amith Yamasani742a6712011-05-04 14:49:28 -07004872 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004873 // Our own process gets to do everything.
4874 if (pid == MY_PID) {
4875 return PackageManager.PERMISSION_GRANTED;
4876 }
4877 synchronized(this) {
4878 return checkUriPermissionLocked(uri, uid, modeFlags)
4879 ? PackageManager.PERMISSION_GRANTED
4880 : PackageManager.PERMISSION_DENIED;
4881 }
4882 }
4883
Dianne Hackborn39792d22010-08-19 18:01:52 -07004884 /**
4885 * Check if the targetPkg can be granted permission to access uri by
4886 * the callingUid using the given modeFlags. Throws a security exception
4887 * if callingUid is not allowed to do this. Returns the uid of the target
4888 * if the URI permission grant should be performed; returns -1 if it is not
4889 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004890 * If you already know the uid of the target, you can supply it in
4891 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004892 */
4893 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004894 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4896 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4897 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004898 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004899 }
4900
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004901 if (targetPkg != null) {
4902 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4903 "Checking grant " + targetPkg + " permission to " + uri);
4904 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004905
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004906 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004907
4908 // If this is not a content: uri, we can't do anything with it.
4909 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004910 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004911 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004912 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004913 }
4914
4915 String name = uri.getAuthority();
4916 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004917 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4918 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004919 if (cpr != null) {
4920 pi = cpr.info;
4921 } else {
4922 try {
4923 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004924 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004925 } catch (RemoteException ex) {
4926 }
4927 }
4928 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004929 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004930 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 }
4932
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004933 int targetUid = lastTargetUid;
4934 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004935 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004936 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004937 if (targetUid < 0) {
4938 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4939 "Can't grant URI permission no uid for: " + targetPkg);
4940 return -1;
4941 }
4942 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004943 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004945 }
4946
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004947 if (targetUid >= 0) {
4948 // First... does the target actually need this permission?
4949 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4950 // No need to grant the target this permission.
4951 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4952 "Target " + targetPkg + " already has full permission to " + uri);
4953 return -1;
4954 }
4955 } else {
4956 // First... there is no target package, so can anyone access it?
4957 boolean allowed = pi.exported;
4958 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4959 if (pi.readPermission != null) {
4960 allowed = false;
4961 }
4962 }
4963 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4964 if (pi.writePermission != null) {
4965 allowed = false;
4966 }
4967 }
4968 if (allowed) {
4969 return -1;
4970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004971 }
4972
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004973 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004974 if (!pi.grantUriPermissions) {
4975 throw new SecurityException("Provider " + pi.packageName
4976 + "/" + pi.name
4977 + " does not allow granting of Uri permissions (uri "
4978 + uri + ")");
4979 }
4980 if (pi.uriPermissionPatterns != null) {
4981 final int N = pi.uriPermissionPatterns.length;
4982 boolean allowed = false;
4983 for (int i=0; i<N; i++) {
4984 if (pi.uriPermissionPatterns[i] != null
4985 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4986 allowed = true;
4987 break;
4988 }
4989 }
4990 if (!allowed) {
4991 throw new SecurityException("Provider " + pi.packageName
4992 + "/" + pi.name
4993 + " does not allow granting of permission to path of Uri "
4994 + uri);
4995 }
4996 }
4997
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004998 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004999 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005000 if (callingUid != Process.myUid()) {
5001 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5002 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5003 throw new SecurityException("Uid " + callingUid
5004 + " does not have permission to uri " + uri);
5005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005006 }
5007 }
5008
Dianne Hackborn39792d22010-08-19 18:01:52 -07005009 return targetUid;
5010 }
5011
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005012 public int checkGrantUriPermission(int callingUid, String targetPkg,
5013 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005014 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005015 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005016 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005017 }
5018 }
5019
Dianne Hackborn39792d22010-08-19 18:01:52 -07005020 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5021 Uri uri, int modeFlags, UriPermissionOwner owner) {
5022 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5023 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5024 if (modeFlags == 0) {
5025 return;
5026 }
5027
5028 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005029 // to the uri, and the target doesn't. Let's now give this to
5030 // the target.
5031
Joe Onorato8a9b2202010-02-26 18:56:32 -08005032 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005033 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005035 HashMap<Uri, UriPermission> targetUris
5036 = mGrantedUriPermissions.get(targetUid);
5037 if (targetUris == null) {
5038 targetUris = new HashMap<Uri, UriPermission>();
5039 mGrantedUriPermissions.put(targetUid, targetUris);
5040 }
5041
5042 UriPermission perm = targetUris.get(uri);
5043 if (perm == null) {
5044 perm = new UriPermission(targetUid, uri);
5045 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005046 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005048 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005049 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005050 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005051 } else {
5052 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5053 perm.readOwners.add(owner);
5054 owner.addReadPermission(perm);
5055 }
5056 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5057 perm.writeOwners.add(owner);
5058 owner.addWritePermission(perm);
5059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005060 }
5061 }
5062
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005063 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5064 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005065 if (targetPkg == null) {
5066 throw new NullPointerException("targetPkg");
5067 }
5068
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005069 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005070 if (targetUid < 0) {
5071 return;
5072 }
5073
5074 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5075 }
5076
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005077 static class NeededUriGrants extends ArrayList<Uri> {
5078 final String targetPkg;
5079 final int targetUid;
5080 final int flags;
5081
5082 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5083 targetPkg = _targetPkg;
5084 targetUid = _targetUid;
5085 flags = _flags;
5086 }
5087 }
5088
Dianne Hackborn39792d22010-08-19 18:01:52 -07005089 /**
5090 * Like checkGrantUriPermissionLocked, but takes an Intent.
5091 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005092 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5093 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005094 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005095 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5096 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005097 + " from " + intent + "; flags=0x"
5098 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5099
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005100 if (targetPkg == null) {
5101 throw new NullPointerException("targetPkg");
5102 }
5103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005104 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005105 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106 }
5107 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005108 ClipData clip = intent.getClipData();
5109 if (data == null && clip == null) {
5110 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005111 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005112 if (data != null) {
5113 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5114 mode, needed != null ? needed.targetUid : -1);
5115 if (target > 0) {
5116 if (needed == null) {
5117 needed = new NeededUriGrants(targetPkg, target, mode);
5118 }
5119 needed.add(data);
5120 }
5121 }
5122 if (clip != null) {
5123 for (int i=0; i<clip.getItemCount(); i++) {
5124 Uri uri = clip.getItemAt(i).getUri();
5125 if (uri != null) {
5126 int target = -1;
5127 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5128 mode, needed != null ? needed.targetUid : -1);
5129 if (target > 0) {
5130 if (needed == null) {
5131 needed = new NeededUriGrants(targetPkg, target, mode);
5132 }
5133 needed.add(uri);
5134 }
5135 } else {
5136 Intent clipIntent = clip.getItemAt(i).getIntent();
5137 if (clipIntent != null) {
5138 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5139 callingUid, targetPkg, clipIntent, mode, needed);
5140 if (newNeeded != null) {
5141 needed = newNeeded;
5142 }
5143 }
5144 }
5145 }
5146 }
5147
5148 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005149 }
5150
5151 /**
5152 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5153 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005154 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5155 UriPermissionOwner owner) {
5156 if (needed != null) {
5157 for (int i=0; i<needed.size(); i++) {
5158 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5159 needed.get(i), needed.flags, owner);
5160 }
5161 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005162 }
5163
5164 void grantUriPermissionFromIntentLocked(int callingUid,
5165 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005166 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005167 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005168 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005169 return;
5170 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005171
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005172 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 }
5174
5175 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5176 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005177 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005178 synchronized(this) {
5179 final ProcessRecord r = getRecordForAppLocked(caller);
5180 if (r == null) {
5181 throw new SecurityException("Unable to find app for caller "
5182 + caller
5183 + " when granting permission to uri " + uri);
5184 }
5185 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005186 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005187 }
5188 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005189 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005190 }
5191
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005192 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005193 null);
5194 }
5195 }
5196
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005197 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005198 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5199 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5200 HashMap<Uri, UriPermission> perms
5201 = mGrantedUriPermissions.get(perm.uid);
5202 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005203 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005204 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205 perms.remove(perm.uri);
5206 if (perms.size() == 0) {
5207 mGrantedUriPermissions.remove(perm.uid);
5208 }
5209 }
5210 }
5211 }
5212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005213 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5214 int modeFlags) {
5215 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5216 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5217 if (modeFlags == 0) {
5218 return;
5219 }
5220
Joe Onorato8a9b2202010-02-26 18:56:32 -08005221 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005222 "Revoking all granted permissions to " + uri);
5223
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005224 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225
5226 final String authority = uri.getAuthority();
5227 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005228 int userId = UserId.getUserId(callingUid);
5229 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005230 if (cpr != null) {
5231 pi = cpr.info;
5232 } else {
5233 try {
5234 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005235 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005236 } catch (RemoteException ex) {
5237 }
5238 }
5239 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005240 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005241 return;
5242 }
5243
5244 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005245 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005246 // Right now, if you are not the original owner of the permission,
5247 // you are not allowed to revoke it.
5248 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5249 throw new SecurityException("Uid " + callingUid
5250 + " does not have permission to uri " + uri);
5251 //}
5252 }
5253
5254 // Go through all of the permissions and remove any that match.
5255 final List<String> SEGMENTS = uri.getPathSegments();
5256 if (SEGMENTS != null) {
5257 final int NS = SEGMENTS.size();
5258 int N = mGrantedUriPermissions.size();
5259 for (int i=0; i<N; i++) {
5260 HashMap<Uri, UriPermission> perms
5261 = mGrantedUriPermissions.valueAt(i);
5262 Iterator<UriPermission> it = perms.values().iterator();
5263 toploop:
5264 while (it.hasNext()) {
5265 UriPermission perm = it.next();
5266 Uri targetUri = perm.uri;
5267 if (!authority.equals(targetUri.getAuthority())) {
5268 continue;
5269 }
5270 List<String> targetSegments = targetUri.getPathSegments();
5271 if (targetSegments == null) {
5272 continue;
5273 }
5274 if (targetSegments.size() < NS) {
5275 continue;
5276 }
5277 for (int j=0; j<NS; j++) {
5278 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5279 continue toploop;
5280 }
5281 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005282 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005283 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005284 perm.clearModes(modeFlags);
5285 if (perm.modeFlags == 0) {
5286 it.remove();
5287 }
5288 }
5289 if (perms.size() == 0) {
5290 mGrantedUriPermissions.remove(
5291 mGrantedUriPermissions.keyAt(i));
5292 N--;
5293 i--;
5294 }
5295 }
5296 }
5297 }
5298
5299 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5300 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005301 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005302 synchronized(this) {
5303 final ProcessRecord r = getRecordForAppLocked(caller);
5304 if (r == null) {
5305 throw new SecurityException("Unable to find app for caller "
5306 + caller
5307 + " when revoking permission to uri " + uri);
5308 }
5309 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005310 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005311 return;
5312 }
5313
5314 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5315 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5316 if (modeFlags == 0) {
5317 return;
5318 }
5319
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005320 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005321
5322 final String authority = uri.getAuthority();
5323 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005324 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005325 if (cpr != null) {
5326 pi = cpr.info;
5327 } else {
5328 try {
5329 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005330 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005331 } catch (RemoteException ex) {
5332 }
5333 }
5334 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005335 Slog.w(TAG, "No content provider found for permission revoke: "
5336 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005337 return;
5338 }
5339
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005340 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005341 }
5342 }
5343
Dianne Hackborn7e269642010-08-25 19:50:20 -07005344 @Override
5345 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005346 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005347 synchronized(this) {
5348 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5349 return owner.getExternalTokenLocked();
5350 }
5351 }
5352
5353 @Override
5354 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5355 Uri uri, int modeFlags) {
5356 synchronized(this) {
5357 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5358 if (owner == null) {
5359 throw new IllegalArgumentException("Unknown owner: " + token);
5360 }
5361 if (fromUid != Binder.getCallingUid()) {
5362 if (Binder.getCallingUid() != Process.myUid()) {
5363 // Only system code can grant URI permissions on behalf
5364 // of other users.
5365 throw new SecurityException("nice try");
5366 }
5367 }
5368 if (targetPkg == null) {
5369 throw new IllegalArgumentException("null target");
5370 }
5371 if (uri == null) {
5372 throw new IllegalArgumentException("null uri");
5373 }
5374
5375 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5376 }
5377 }
5378
5379 @Override
5380 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5381 synchronized(this) {
5382 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5383 if (owner == null) {
5384 throw new IllegalArgumentException("Unknown owner: " + token);
5385 }
5386
5387 if (uri == null) {
5388 owner.removeUriPermissionsLocked(mode);
5389 } else {
5390 owner.removeUriPermissionLocked(uri, mode);
5391 }
5392 }
5393 }
5394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005395 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5396 synchronized (this) {
5397 ProcessRecord app =
5398 who != null ? getRecordForAppLocked(who) : null;
5399 if (app == null) return;
5400
5401 Message msg = Message.obtain();
5402 msg.what = WAIT_FOR_DEBUGGER_MSG;
5403 msg.obj = app;
5404 msg.arg1 = waiting ? 1 : 0;
5405 mHandler.sendMessage(msg);
5406 }
5407 }
5408
5409 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005410 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5411 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005412 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005413 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005414 outInfo.threshold = homeAppMem;
5415 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5416 outInfo.hiddenAppThreshold = hiddenAppMem;
5417 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005418 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005419 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5420 ProcessList.VISIBLE_APP_ADJ);
5421 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5422 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005423 }
5424
5425 // =========================================================
5426 // TASK MANAGEMENT
5427 // =========================================================
5428
5429 public List getTasks(int maxNum, int flags,
5430 IThumbnailReceiver receiver) {
5431 ArrayList list = new ArrayList();
5432
5433 PendingThumbnailsRecord pending = null;
5434 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005435 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436
5437 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005438 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5440 + ", receiver=" + receiver);
5441
5442 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5443 != PackageManager.PERMISSION_GRANTED) {
5444 if (receiver != null) {
5445 // If the caller wants to wait for pending thumbnails,
5446 // it ain't gonna get them.
5447 try {
5448 receiver.finished();
5449 } catch (RemoteException ex) {
5450 }
5451 }
5452 String msg = "Permission Denial: getTasks() from pid="
5453 + Binder.getCallingPid()
5454 + ", uid=" + Binder.getCallingUid()
5455 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005456 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 throw new SecurityException(msg);
5458 }
5459
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005460 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005461 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005462 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005463 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 TaskRecord curTask = null;
5465 int numActivities = 0;
5466 int numRunning = 0;
5467 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005468 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005469 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005470 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005471
5472 // Initialize state for next task if needed.
5473 if (top == null ||
5474 (top.state == ActivityState.INITIALIZING
5475 && top.task == r.task)) {
5476 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005477 curTask = r.task;
5478 numActivities = numRunning = 0;
5479 }
5480
5481 // Add 'r' into the current task.
5482 numActivities++;
5483 if (r.app != null && r.app.thread != null) {
5484 numRunning++;
5485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005486
Joe Onorato8a9b2202010-02-26 18:56:32 -08005487 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 TAG, r.intent.getComponent().flattenToShortString()
5489 + ": task=" + r.task);
5490
5491 // If the next one is a different task, generate a new
5492 // TaskInfo entry for what we have.
5493 if (next == null || next.task != curTask) {
5494 ActivityManager.RunningTaskInfo ci
5495 = new ActivityManager.RunningTaskInfo();
5496 ci.id = curTask.taskId;
5497 ci.baseActivity = r.intent.getComponent();
5498 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005499 if (top.thumbHolder != null) {
5500 ci.description = top.thumbHolder.lastDescription;
5501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005502 ci.numActivities = numActivities;
5503 ci.numRunning = numRunning;
5504 //System.out.println(
5505 // "#" + maxNum + ": " + " descr=" + ci.description);
5506 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005507 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005508 TAG, "State=" + top.state + "Idle=" + top.idle
5509 + " app=" + top.app
5510 + " thr=" + (top.app != null ? top.app.thread : null));
5511 if (top.state == ActivityState.RESUMED
5512 || top.state == ActivityState.PAUSING) {
5513 if (top.idle && top.app != null
5514 && top.app.thread != null) {
5515 topRecord = top;
5516 topThumbnail = top.app.thread;
5517 } else {
5518 top.thumbnailNeeded = true;
5519 }
5520 }
5521 if (pending == null) {
5522 pending = new PendingThumbnailsRecord(receiver);
5523 }
5524 pending.pendingRecords.add(top);
5525 }
5526 list.add(ci);
5527 maxNum--;
5528 top = null;
5529 }
5530 }
5531
5532 if (pending != null) {
5533 mPendingThumbnails.add(pending);
5534 }
5535 }
5536
Joe Onorato8a9b2202010-02-26 18:56:32 -08005537 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005538
5539 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005540 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005542 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005544 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005545 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005546 }
5547 }
5548
5549 if (pending == null && receiver != null) {
5550 // In this case all thumbnails were available and the client
5551 // is being asked to be told when the remaining ones come in...
5552 // which is unusually, since the top-most currently running
5553 // activity should never have a canned thumbnail! Oh well.
5554 try {
5555 receiver.finished();
5556 } catch (RemoteException ex) {
5557 }
5558 }
5559
5560 return list;
5561 }
5562
5563 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5564 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005565 final int callingUid = Binder.getCallingUid();
5566 // If it's the system uid asking, then use the current user id.
5567 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5568 // require the entire list.
5569 final int callingUserId = callingUid == Process.SYSTEM_UID
5570 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571 synchronized (this) {
5572 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5573 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005574 final boolean detailed = checkCallingPermission(
5575 android.Manifest.permission.GET_DETAILED_TASKS)
5576 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005578 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005580 final int N = mRecentTasks.size();
5581 ArrayList<ActivityManager.RecentTaskInfo> res
5582 = new ArrayList<ActivityManager.RecentTaskInfo>(
5583 maxNum < N ? maxNum : N);
5584 for (int i=0; i<N && maxNum > 0; i++) {
5585 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005586 // Only add calling user's recent tasks
5587 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005588 // Return the entry if desired by the caller. We always return
5589 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005590 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005591 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5592 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005593
Dianne Hackborn905577f2011-09-07 18:31:28 -07005594 if (i == 0
5595 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 || (tr.intent == null)
5597 || ((tr.intent.getFlags()
5598 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5599 ActivityManager.RecentTaskInfo rti
5600 = new ActivityManager.RecentTaskInfo();
5601 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005602 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 rti.baseIntent = new Intent(
5604 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005605 if (!detailed) {
5606 rti.baseIntent.replaceExtras((Bundle)null);
5607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005609 rti.description = tr.lastDescription;
5610
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005611 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5612 // Check whether this activity is currently available.
5613 try {
5614 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005615 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5616 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005617 continue;
5618 }
5619 } else if (rti.baseIntent != null) {
5620 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005621 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005622 continue;
5623 }
5624 }
5625 } catch (RemoteException e) {
5626 // Will never happen.
5627 }
5628 }
5629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 res.add(rti);
5631 maxNum--;
5632 }
5633 }
5634 return res;
5635 }
5636 }
5637
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005638 private TaskRecord taskForIdLocked(int id) {
5639 final int N = mRecentTasks.size();
5640 for (int i=0; i<N; i++) {
5641 TaskRecord tr = mRecentTasks.get(i);
5642 if (tr.taskId == id) {
5643 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005644 }
5645 }
5646 return null;
5647 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005648
5649 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5650 synchronized (this) {
5651 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5652 "getTaskThumbnails()");
5653 TaskRecord tr = taskForIdLocked(id);
5654 if (tr != null) {
5655 return mMainStack.getTaskThumbnailsLocked(tr);
5656 }
5657 }
5658 return null;
5659 }
5660
5661 public boolean removeSubTask(int taskId, int subTaskIndex) {
5662 synchronized (this) {
5663 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5664 "removeSubTask()");
5665 long ident = Binder.clearCallingIdentity();
5666 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005667 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5668 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005669 } finally {
5670 Binder.restoreCallingIdentity(ident);
5671 }
5672 }
5673 }
5674
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005675 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5676 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005677 Intent baseIntent = new Intent(
5678 tr.intent != null ? tr.intent : tr.affinityIntent);
5679 ComponentName component = baseIntent.getComponent();
5680 if (component == null) {
5681 Slog.w(TAG, "Now component for base intent of task: " + tr);
5682 return;
5683 }
5684
5685 // Find any running services associated with this app.
5686 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005687 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005688 if (sr.packageName.equals(component.getPackageName())) {
5689 services.add(sr);
5690 }
5691 }
5692
5693 // Take care of any running services associated with the app.
5694 for (int i=0; i<services.size(); i++) {
5695 ServiceRecord sr = services.get(i);
5696 if (sr.startRequested) {
5697 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005698 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005699 stopServiceLocked(sr);
5700 } else {
5701 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005702 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005703 if (sr.app != null && sr.app.thread != null) {
5704 sendServiceArgsLocked(sr, false);
5705 }
5706 }
5707 }
5708 }
5709
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005710 if (killProcesses) {
5711 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005712 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005713 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005714 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5715 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5716 for (int i=0; i<uids.size(); i++) {
5717 ProcessRecord proc = uids.valueAt(i);
5718 if (proc.userId != tr.userId) {
5719 continue;
5720 }
5721 if (!proc.pkgList.contains(pkg)) {
5722 continue;
5723 }
5724 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005725 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005726 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005727
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005728 // Kill the running processes.
5729 for (int i=0; i<procs.size(); i++) {
5730 ProcessRecord pr = procs.get(i);
5731 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5732 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5733 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5734 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005735 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005736 Process.killProcessQuiet(pr.pid);
5737 } else {
5738 pr.waitingToKill = "remove task";
5739 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005740 }
5741 }
5742 }
5743
5744 public boolean removeTask(int taskId, int flags) {
5745 synchronized (this) {
5746 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5747 "removeTask()");
5748 long ident = Binder.clearCallingIdentity();
5749 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005750 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5751 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005752 if (r != null) {
5753 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005754 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005755 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005756 } else {
5757 TaskRecord tr = null;
5758 int i=0;
5759 while (i < mRecentTasks.size()) {
5760 TaskRecord t = mRecentTasks.get(i);
5761 if (t.taskId == taskId) {
5762 tr = t;
5763 break;
5764 }
5765 i++;
5766 }
5767 if (tr != null) {
5768 if (tr.numActivities <= 0) {
5769 // Caller is just removing a recent task that is
5770 // not actively running. That is easy!
5771 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005772 cleanUpRemovedTaskLocked(tr, flags);
5773 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005774 } else {
5775 Slog.w(TAG, "removeTask: task " + taskId
5776 + " does not have activities to remove, "
5777 + " but numActivities=" + tr.numActivities
5778 + ": " + tr);
5779 }
5780 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005781 }
5782 } finally {
5783 Binder.restoreCallingIdentity(ident);
5784 }
5785 }
5786 return false;
5787 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5790 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005791 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005792 TaskRecord jt = startTask;
5793
5794 // First look backwards
5795 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005796 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 if (r.task != jt) {
5798 jt = r.task;
5799 if (affinity.equals(jt.affinity)) {
5800 return j;
5801 }
5802 }
5803 }
5804
5805 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005806 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005807 jt = startTask;
5808 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005809 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005810 if (r.task != jt) {
5811 if (affinity.equals(jt.affinity)) {
5812 return j;
5813 }
5814 jt = r.task;
5815 }
5816 }
5817
5818 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005819 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 return N-1;
5821 }
5822
5823 return -1;
5824 }
5825
5826 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005827 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005829 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005830 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5831 "moveTaskToFront()");
5832
5833 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005834 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5835 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005836 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005837 return;
5838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 final long origId = Binder.clearCallingIdentity();
5840 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005841 TaskRecord tr = taskForIdLocked(task);
5842 if (tr != null) {
5843 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5844 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005846 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5847 // Caller wants the home activity moved with it. To accomplish this,
5848 // we'll just move the home task to the top first.
5849 mMainStack.moveHomeToFrontLocked();
5850 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005851 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005852 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005854 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5855 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005857 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5858 mMainStack.mUserLeaving = true;
5859 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005860 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5861 // Caller wants the home activity moved with it. To accomplish this,
5862 // we'll just move the home task to the top first.
5863 mMainStack.moveHomeToFrontLocked();
5864 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005865 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 return;
5867 }
5868 }
5869 } finally {
5870 Binder.restoreCallingIdentity(origId);
5871 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005872 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 }
5874 }
5875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005876 public void moveTaskToBack(int task) {
5877 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5878 "moveTaskToBack()");
5879
5880 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005881 if (mMainStack.mResumedActivity != null
5882 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005883 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5884 Binder.getCallingUid(), "Task to back")) {
5885 return;
5886 }
5887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005889 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 Binder.restoreCallingIdentity(origId);
5891 }
5892 }
5893
5894 /**
5895 * Moves an activity, and all of the other activities within the same task, to the bottom
5896 * of the history stack. The activity's order within the task is unchanged.
5897 *
5898 * @param token A reference to the activity we wish to move
5899 * @param nonRoot If false then this only works if the activity is the root
5900 * of a task; if true it will work for any activity in a task.
5901 * @return Returns true if the move completed, false if not.
5902 */
5903 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005904 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005905 synchronized(this) {
5906 final long origId = Binder.clearCallingIdentity();
5907 int taskId = getTaskForActivityLocked(token, !nonRoot);
5908 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005909 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005910 }
5911 Binder.restoreCallingIdentity(origId);
5912 }
5913 return false;
5914 }
5915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005916 public void moveTaskBackwards(int task) {
5917 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5918 "moveTaskBackwards()");
5919
5920 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005921 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5922 Binder.getCallingUid(), "Task backwards")) {
5923 return;
5924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 final long origId = Binder.clearCallingIdentity();
5926 moveTaskBackwardsLocked(task);
5927 Binder.restoreCallingIdentity(origId);
5928 }
5929 }
5930
5931 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005932 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005933 }
5934
5935 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5936 synchronized(this) {
5937 return getTaskForActivityLocked(token, onlyRoot);
5938 }
5939 }
5940
5941 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005942 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005943 TaskRecord lastTask = null;
5944 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005945 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005946 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 if (!onlyRoot || lastTask != r.task) {
5948 return r.task.taskId;
5949 }
5950 return -1;
5951 }
5952 lastTask = r.task;
5953 }
5954
5955 return -1;
5956 }
5957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005958 // =========================================================
5959 // THUMBNAILS
5960 // =========================================================
5961
5962 public void reportThumbnail(IBinder token,
5963 Bitmap thumbnail, CharSequence description) {
5964 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5965 final long origId = Binder.clearCallingIdentity();
5966 sendPendingThumbnail(null, token, thumbnail, description, true);
5967 Binder.restoreCallingIdentity(origId);
5968 }
5969
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005970 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005971 Bitmap thumbnail, CharSequence description, boolean always) {
5972 TaskRecord task = null;
5973 ArrayList receivers = null;
5974
5975 //System.out.println("Send pending thumbnail: " + r);
5976
5977 synchronized(this) {
5978 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005979 r = mMainStack.isInStackLocked(token);
5980 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 return;
5982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005984 if (thumbnail == null && r.thumbHolder != null) {
5985 thumbnail = r.thumbHolder.lastThumbnail;
5986 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 }
5988 if (thumbnail == null && !always) {
5989 // If there is no thumbnail, and this entry is not actually
5990 // going away, then abort for now and pick up the next
5991 // thumbnail we get.
5992 return;
5993 }
5994 task = r.task;
5995
5996 int N = mPendingThumbnails.size();
5997 int i=0;
5998 while (i<N) {
5999 PendingThumbnailsRecord pr =
6000 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6001 //System.out.println("Looking in " + pr.pendingRecords);
6002 if (pr.pendingRecords.remove(r)) {
6003 if (receivers == null) {
6004 receivers = new ArrayList();
6005 }
6006 receivers.add(pr);
6007 if (pr.pendingRecords.size() == 0) {
6008 pr.finished = true;
6009 mPendingThumbnails.remove(i);
6010 N--;
6011 continue;
6012 }
6013 }
6014 i++;
6015 }
6016 }
6017
6018 if (receivers != null) {
6019 final int N = receivers.size();
6020 for (int i=0; i<N; i++) {
6021 try {
6022 PendingThumbnailsRecord pr =
6023 (PendingThumbnailsRecord)receivers.get(i);
6024 pr.receiver.newThumbnail(
6025 task != null ? task.taskId : -1, thumbnail, description);
6026 if (pr.finished) {
6027 pr.receiver.finished();
6028 }
6029 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006030 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 }
6032 }
6033 }
6034 }
6035
6036 // =========================================================
6037 // CONTENT PROVIDERS
6038 // =========================================================
6039
Jeff Brown10e89712011-07-08 18:52:57 -07006040 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6041 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006043 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006044 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006045 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 } catch (RemoteException ex) {
6047 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006048 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006049 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6050 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 if (providers != null) {
6052 final int N = providers.size();
6053 for (int i=0; i<N; i++) {
6054 ProviderInfo cpi =
6055 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07006056
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006057 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006058 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006060 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07006061 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006062 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006063 if (DEBUG_MU)
6064 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006065 app.pubProviders.put(cpi.name, cpr);
6066 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006067 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006068 }
6069 }
6070 return providers;
6071 }
6072
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006073 /**
6074 * Check if {@link ProcessRecord} has a possible chance at accessing the
6075 * given {@link ProviderInfo}. Final permission checking is always done
6076 * in {@link ContentProvider}.
6077 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006079 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006080 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006081 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006083 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006084 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 return null;
6086 }
6087 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006088 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 == PackageManager.PERMISSION_GRANTED) {
6090 return null;
6091 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006092
6093 PathPermission[] pps = cpi.pathPermissions;
6094 if (pps != null) {
6095 int i = pps.length;
6096 while (i > 0) {
6097 i--;
6098 PathPermission pp = pps[i];
6099 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006100 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006101 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006102 return null;
6103 }
6104 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006105 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006106 == PackageManager.PERMISSION_GRANTED) {
6107 return null;
6108 }
6109 }
6110 }
6111
Dianne Hackbornb424b632010-08-18 15:59:05 -07006112 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6113 if (perms != null) {
6114 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6115 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6116 return null;
6117 }
6118 }
6119 }
6120
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006121 String msg;
6122 if (!cpi.exported) {
6123 msg = "Permission Denial: opening provider " + cpi.name
6124 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6125 + ", uid=" + callingUid + ") that is not exported from uid "
6126 + cpi.applicationInfo.uid;
6127 } else {
6128 msg = "Permission Denial: opening provider " + cpi.name
6129 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6130 + ", uid=" + callingUid + ") requires "
6131 + cpi.readPermission + " or " + cpi.writePermission;
6132 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006133 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006134 return msg;
6135 }
6136
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006137 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6138 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006139 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006140 for (int i=0; i<r.conProviders.size(); i++) {
6141 ContentProviderConnection conn = r.conProviders.get(i);
6142 if (conn.provider == cpr) {
6143 if (DEBUG_PROVIDER) Slog.v(TAG,
6144 "Adding provider requested by "
6145 + r.processName + " from process "
6146 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6147 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6148 if (stable) {
6149 conn.stableCount++;
6150 conn.numStableIncs++;
6151 } else {
6152 conn.unstableCount++;
6153 conn.numUnstableIncs++;
6154 }
6155 return conn;
6156 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006157 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006158 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6159 if (stable) {
6160 conn.stableCount = 1;
6161 conn.numStableIncs = 1;
6162 } else {
6163 conn.unstableCount = 1;
6164 conn.numUnstableIncs = 1;
6165 }
6166 cpr.connections.add(conn);
6167 r.conProviders.add(conn);
6168 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006169 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006170 cpr.addExternalProcessHandleLocked(externalProcessToken);
6171 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006172 }
6173
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006174 boolean decProviderCountLocked(ContentProviderConnection conn,
6175 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6176 if (conn != null) {
6177 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006178 if (DEBUG_PROVIDER) Slog.v(TAG,
6179 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006180 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006181 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006182 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6183 if (stable) {
6184 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006185 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006186 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006187 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006188 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6189 cpr.connections.remove(conn);
6190 conn.client.conProviders.remove(conn);
6191 return true;
6192 }
6193 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006194 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006195 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006196 return false;
6197 }
6198
Amith Yamasani742a6712011-05-04 14:49:28 -07006199 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006200 String name, IBinder token, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006202 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 ProviderInfo cpi = null;
6204
6205 synchronized(this) {
6206 ProcessRecord r = null;
6207 if (caller != null) {
6208 r = getRecordForAppLocked(caller);
6209 if (r == null) {
6210 throw new SecurityException(
6211 "Unable to find app for caller " + caller
6212 + " (pid=" + Binder.getCallingPid()
6213 + ") when getting content provider " + name);
6214 }
6215 }
6216
6217 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006218 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006219 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006220 boolean providerRunning = cpr != null;
6221 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006223 String msg;
6224 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6225 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 }
6227
6228 if (r != null && cpr.canRunHere(r)) {
6229 // This provider has been published or is in the process
6230 // of being published... but it is also allowed to run
6231 // in the caller's process, so don't make a connection
6232 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006233 ContentProviderHolder holder = cpr.newHolder(null);
6234 // don't give caller the provider object, it needs
6235 // to make its own.
6236 holder.provider = null;
6237 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 }
6239
6240 final long origId = Binder.clearCallingIdentity();
6241
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006242 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006244 conn = incProviderCountLocked(r, cpr, token, stable);
6245 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006246 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006247 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006248 // make sure to count it as being accessed and thus
6249 // back up on the LRU list. This is good because
6250 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006251 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006252 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006253 }
6254
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006255 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006256 if (false) {
6257 if (cpr.name.flattenToShortString().equals(
6258 "com.android.providers.calendar/.CalendarProvider2")) {
6259 Slog.v(TAG, "****************** KILLING "
6260 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006261 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006262 }
6263 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006264 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006265 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6266 // NOTE: there is still a race here where a signal could be
6267 // pending on the process even though we managed to update its
6268 // adj level. Not sure what to do about this, but at least
6269 // the race is now smaller.
6270 if (!success) {
6271 // Uh oh... it looks like the provider's process
6272 // has been killed on us. We need to wait for a new
6273 // process to be started, and make sure its death
6274 // doesn't kill our process.
6275 Slog.i(TAG,
6276 "Existing provider " + cpr.name.flattenToShortString()
6277 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006278 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006279 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006280 if (!lastRef) {
6281 // This wasn't the last ref our process had on
6282 // the provider... we have now been killed, bail.
6283 return null;
6284 }
6285 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006286 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 }
6289
6290 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006293 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006294 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006295 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006296 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006297 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006298 } catch (RemoteException ex) {
6299 }
6300 if (cpi == null) {
6301 return null;
6302 }
Amith Yamasania4a54e22012-04-16 15:44:19 -07006303 if (isSingleton(cpi.processName, cpi.applicationInfo)) {
6304 userId = 0;
6305 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006306 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006307
Dianne Hackbornb424b632010-08-18 15:59:05 -07006308 String msg;
6309 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6310 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 }
6312
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006313 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006314 && !cpi.processName.equals("system")) {
6315 // If this content provider does not run in the system
6316 // process, and the system is not yet ready to run other
6317 // processes, then fail fast instead of hanging.
6318 throw new IllegalArgumentException(
6319 "Attempt to launch content provider before system ready");
6320 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006321
6322 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006323 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 final boolean firstClass = cpr == null;
6325 if (firstClass) {
6326 try {
6327 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006328 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 getApplicationInfo(
6330 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006331 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006333 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 + cpi.name);
6335 return null;
6336 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006337 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006338 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 } catch (RemoteException ex) {
6340 // pm is in same process, this will never happen.
6341 }
6342 }
6343
6344 if (r != null && cpr.canRunHere(r)) {
6345 // If this is a multiprocess provider, then just return its
6346 // info and allow the caller to instantiate it. Only do
6347 // this if the provider is the same user as the caller's
6348 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006349 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006350 }
6351
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006352 if (DEBUG_PROVIDER) {
6353 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006354 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006355 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006356 }
6357
6358 // This is single process, and our app is now connecting to it.
6359 // See if we are already in the process of launching this
6360 // provider.
6361 final int N = mLaunchingProviders.size();
6362 int i;
6363 for (i=0; i<N; i++) {
6364 if (mLaunchingProviders.get(i) == cpr) {
6365 break;
6366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 }
6368
6369 // If the provider is not already being launched, then get it
6370 // started.
6371 if (i >= N) {
6372 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006373
6374 try {
6375 // Content provider is now in use, its package can't be stopped.
6376 try {
6377 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006378 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006379 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006380 } catch (IllegalArgumentException e) {
6381 Slog.w(TAG, "Failed trying to unstop package "
6382 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006383 }
6384
6385 ProcessRecord proc = startProcessLocked(cpi.processName,
6386 cpr.appInfo, false, 0, "content provider",
6387 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006388 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006389 if (proc == null) {
6390 Slog.w(TAG, "Unable to launch app "
6391 + cpi.applicationInfo.packageName + "/"
6392 + cpi.applicationInfo.uid + " for provider "
6393 + name + ": process is bad");
6394 return null;
6395 }
6396 cpr.launchingApp = proc;
6397 mLaunchingProviders.add(cpr);
6398 } finally {
6399 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 }
6402
6403 // Make sure the provider is published (the same provider class
6404 // may be published under multiple names).
6405 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006406 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006408
Amith Yamasani742a6712011-05-04 14:49:28 -07006409 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006410 conn = incProviderCountLocked(r, cpr, token, stable);
6411 if (conn != null) {
6412 conn.waiting = true;
6413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 }
6415 }
6416
6417 // Wait for the provider to be published...
6418 synchronized (cpr) {
6419 while (cpr.provider == null) {
6420 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006421 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 + cpi.applicationInfo.packageName + "/"
6423 + cpi.applicationInfo.uid + " for provider "
6424 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006425 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006426 cpi.applicationInfo.packageName,
6427 cpi.applicationInfo.uid, name);
6428 return null;
6429 }
6430 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006431 if (DEBUG_MU) {
6432 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6433 + cpr.launchingApp);
6434 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006435 if (conn != null) {
6436 conn.waiting = true;
6437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006438 cpr.wait();
6439 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006440 } finally {
6441 if (conn != null) {
6442 conn.waiting = false;
6443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 }
6445 }
6446 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006447 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 }
6449
6450 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006451 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006452 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 if (caller == null) {
6454 String msg = "null IApplicationThread when getting content provider "
6455 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006456 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 throw new SecurityException(msg);
6458 }
6459
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006460 return getContentProviderImpl(caller, name, null, stable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006461 }
6462
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006463 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6464 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6465 "Do not have permission in call getContentProviderExternal()");
6466 return getContentProviderExternalUnchecked(name, token);
6467 }
6468
6469 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006470 return getContentProviderImpl(null, name, token, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 }
6472
6473 /**
6474 * Drop a content provider from a ProcessRecord's bookkeeping
6475 * @param cpr
6476 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006477 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006478 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006480 ContentProviderConnection conn;
6481 try {
6482 conn = (ContentProviderConnection)connection;
6483 } catch (ClassCastException e) {
6484 String msg ="removeContentProvider: " + connection
6485 + " not a ContentProviderConnection";
6486 Slog.w(TAG, msg);
6487 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006489 if (conn == null) {
6490 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006492 if (decProviderCountLocked(conn, null, null, stable)) {
6493 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 }
6496 }
6497
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006498 public void removeContentProviderExternal(String name, IBinder token) {
6499 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6500 "Do not have permission in call removeContentProviderExternal()");
6501 removeContentProviderExternalUnchecked(name, token);
6502 }
6503
6504 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006505 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006506 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6507 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 if(cpr == null) {
6509 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006510 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 return;
6512 }
6513
6514 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006515 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006516 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6517 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006518 if (localCpr.hasExternalProcessHandles()) {
6519 if (localCpr.removeExternalProcessHandleLocked(token)) {
6520 updateOomAdjLocked();
6521 } else {
6522 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6523 + " with no external reference for token: "
6524 + token + ".");
6525 }
6526 } else {
6527 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6528 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006530 }
6531 }
6532
6533 public final void publishContentProviders(IApplicationThread caller,
6534 List<ContentProviderHolder> providers) {
6535 if (providers == null) {
6536 return;
6537 }
6538
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006539 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006540 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006542 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006543 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 if (r == null) {
6545 throw new SecurityException(
6546 "Unable to find app for caller " + caller
6547 + " (pid=" + Binder.getCallingPid()
6548 + ") when publishing content providers");
6549 }
6550
6551 final long origId = Binder.clearCallingIdentity();
6552
6553 final int N = providers.size();
6554 for (int i=0; i<N; i++) {
6555 ContentProviderHolder src = providers.get(i);
6556 if (src == null || src.info == null || src.provider == null) {
6557 continue;
6558 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006559 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006560 if (DEBUG_MU)
6561 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006562 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006563 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006564 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006565 String names[] = dst.info.authority.split(";");
6566 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006567 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 }
6569
6570 int NL = mLaunchingProviders.size();
6571 int j;
6572 for (j=0; j<NL; j++) {
6573 if (mLaunchingProviders.get(j) == dst) {
6574 mLaunchingProviders.remove(j);
6575 j--;
6576 NL--;
6577 }
6578 }
6579 synchronized (dst) {
6580 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006581 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006582 dst.notifyAll();
6583 }
6584 updateOomAdjLocked(r);
6585 }
6586 }
6587
6588 Binder.restoreCallingIdentity(origId);
6589 }
6590 }
6591
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006592 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6593 ContentProviderConnection conn;
6594 try {
6595 conn = (ContentProviderConnection)connection;
6596 } catch (ClassCastException e) {
6597 String msg ="refContentProvider: " + connection
6598 + " not a ContentProviderConnection";
6599 Slog.w(TAG, msg);
6600 throw new IllegalArgumentException(msg);
6601 }
6602 if (conn == null) {
6603 throw new NullPointerException("connection is null");
6604 }
6605
6606 synchronized (this) {
6607 if (stable > 0) {
6608 conn.numStableIncs += stable;
6609 }
6610 stable = conn.stableCount + stable;
6611 if (stable < 0) {
6612 throw new IllegalStateException("stableCount < 0: " + stable);
6613 }
6614
6615 if (unstable > 0) {
6616 conn.numUnstableIncs += unstable;
6617 }
6618 unstable = conn.unstableCount + unstable;
6619 if (unstable < 0) {
6620 throw new IllegalStateException("unstableCount < 0: " + unstable);
6621 }
6622
6623 if ((stable+unstable) <= 0) {
6624 throw new IllegalStateException("ref counts can't go to zero here: stable="
6625 + stable + " unstable=" + unstable);
6626 }
6627 conn.stableCount = stable;
6628 conn.unstableCount = unstable;
6629 return !conn.dead;
6630 }
6631 }
6632
6633 public void unstableProviderDied(IBinder connection) {
6634 ContentProviderConnection conn;
6635 try {
6636 conn = (ContentProviderConnection)connection;
6637 } catch (ClassCastException e) {
6638 String msg ="refContentProvider: " + connection
6639 + " not a ContentProviderConnection";
6640 Slog.w(TAG, msg);
6641 throw new IllegalArgumentException(msg);
6642 }
6643 if (conn == null) {
6644 throw new NullPointerException("connection is null");
6645 }
6646
6647 // Safely retrieve the content provider associated with the connection.
6648 IContentProvider provider;
6649 synchronized (this) {
6650 provider = conn.provider.provider;
6651 }
6652
6653 if (provider == null) {
6654 // Um, yeah, we're way ahead of you.
6655 return;
6656 }
6657
6658 // Make sure the caller is being honest with us.
6659 if (provider.asBinder().pingBinder()) {
6660 // Er, no, still looks good to us.
6661 synchronized (this) {
6662 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6663 + " says " + conn + " died, but we don't agree");
6664 return;
6665 }
6666 }
6667
6668 // Well look at that! It's dead!
6669 synchronized (this) {
6670 if (conn.provider.provider != provider) {
6671 // But something changed... good enough.
6672 return;
6673 }
6674
6675 ProcessRecord proc = conn.provider.proc;
6676 if (proc == null || proc.thread == null) {
6677 // Seems like the process is already cleaned up.
6678 return;
6679 }
6680
6681 // As far as we're concerned, this is just like receiving a
6682 // death notification... just a bit prematurely.
6683 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6684 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006685 final long ident = Binder.clearCallingIdentity();
6686 try {
6687 appDiedLocked(proc, proc.pid, proc.thread);
6688 } finally {
6689 Binder.restoreCallingIdentity(ident);
6690 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006691 }
6692 }
6693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006695 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006696 synchronized (mSelf) {
6697 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6698 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006699 if (providers != null) {
6700 for (int i=providers.size()-1; i>=0; i--) {
6701 ProviderInfo pi = (ProviderInfo)providers.get(i);
6702 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6703 Slog.w(TAG, "Not installing system proc provider " + pi.name
6704 + ": not system .apk");
6705 providers.remove(i);
6706 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006707 }
6708 }
6709 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006710 if (providers != null) {
6711 mSystemThread.installSystemProviders(providers);
6712 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006713
6714 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006715
6716 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 }
6718
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006719 /**
6720 * Allows app to retrieve the MIME type of a URI without having permission
6721 * to access its content provider.
6722 *
6723 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6724 *
6725 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6726 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6727 */
6728 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006729 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006730 final String name = uri.getAuthority();
6731 final long ident = Binder.clearCallingIdentity();
6732 ContentProviderHolder holder = null;
6733
6734 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006735 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006736 if (holder != null) {
6737 return holder.provider.getType(uri);
6738 }
6739 } catch (RemoteException e) {
6740 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6741 return null;
6742 } finally {
6743 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006744 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006745 }
6746 Binder.restoreCallingIdentity(ident);
6747 }
6748
6749 return null;
6750 }
6751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 // =========================================================
6753 // GLOBAL MANAGEMENT
6754 // =========================================================
6755
6756 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006757 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758 String proc = customProcess != null ? customProcess : info.processName;
6759 BatteryStatsImpl.Uid.Proc ps = null;
6760 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006761 int uid = info.uid;
6762 if (isolated) {
6763 int userId = UserId.getUserId(uid);
6764 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6765 uid = 0;
6766 while (true) {
6767 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6768 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6769 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6770 }
6771 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6772 mNextIsolatedProcessUid++;
6773 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6774 // No process for this uid, use it.
6775 break;
6776 }
6777 stepsLeft--;
6778 if (stepsLeft <= 0) {
6779 return null;
6780 }
6781 }
6782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 synchronized (stats) {
6784 ps = stats.getProcessStatsLocked(info.uid, proc);
6785 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006786 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006787 }
6788
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006789 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6790 ProcessRecord app;
6791 if (!isolated) {
6792 app = getProcessRecordLocked(info.processName, info.uid);
6793 } else {
6794 app = null;
6795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796
6797 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006798 app = newProcessRecordLocked(null, info, null, isolated);
6799 mProcessNames.put(info.processName, app.uid, app);
6800 if (isolated) {
6801 mIsolatedProcesses.put(app.uid, app);
6802 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006803 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006804 }
6805
Dianne Hackborne7f97212011-02-24 14:40:20 -08006806 // This package really, really can not be stopped.
6807 try {
6808 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006809 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006810 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006811 } catch (IllegalArgumentException e) {
6812 Slog.w(TAG, "Failed trying to unstop package "
6813 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006814 }
6815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006816 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6817 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6818 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006819 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006820 }
6821 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6822 mPersistentStartingProcesses.add(app);
6823 startProcessLocked(app, "added application", app.processName);
6824 }
6825
6826 return app;
6827 }
6828
6829 public void unhandledBack() {
6830 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6831 "unhandledBack()");
6832
6833 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006834 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006835 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 TAG, "Performing unhandledBack(): stack size = " + count);
6837 if (count > 1) {
6838 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006839 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6841 Binder.restoreCallingIdentity(origId);
6842 }
6843 }
6844 }
6845
6846 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006847 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006848 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006849 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006850 ParcelFileDescriptor pfd = null;
6851 if (cph != null) {
6852 // We record the binder invoker's uid in thread-local storage before
6853 // going to the content provider to open the file. Later, in the code
6854 // that handles all permissions checks, we look for this uid and use
6855 // that rather than the Activity Manager's own uid. The effect is that
6856 // we do the check against the caller's permissions even though it looks
6857 // to the content provider like the Activity Manager itself is making
6858 // the request.
6859 sCallerIdentity.set(new Identity(
6860 Binder.getCallingPid(), Binder.getCallingUid()));
6861 try {
6862 pfd = cph.provider.openFile(uri, "r");
6863 } catch (FileNotFoundException e) {
6864 // do nothing; pfd will be returned null
6865 } finally {
6866 // Ensure that whatever happens, we clean up the identity state
6867 sCallerIdentity.remove();
6868 }
6869
6870 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006871 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006872 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006873 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 }
6875 return pfd;
6876 }
6877
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006878 // Actually is sleeping or shutting down or whatever else in the future
6879 // is an inactive state.
6880 public boolean isSleeping() {
6881 return mSleeping || mShuttingDown;
6882 }
6883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006884 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006885 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6886 != PackageManager.PERMISSION_GRANTED) {
6887 throw new SecurityException("Requires permission "
6888 + android.Manifest.permission.DEVICE_POWER);
6889 }
6890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006891 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006892 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006893 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006894
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006895 if (!mSleeping) {
6896 mSleeping = true;
6897 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006898
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006899 // Initialize the wake times of all processes.
6900 checkExcessivePowerUsageLocked(false);
6901 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6902 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6903 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006905 }
6906 }
6907
Dianne Hackborn55280a92009-05-07 15:53:46 -07006908 public boolean shutdown(int timeout) {
6909 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6910 != PackageManager.PERMISSION_GRANTED) {
6911 throw new SecurityException("Requires permission "
6912 + android.Manifest.permission.SHUTDOWN);
6913 }
6914
6915 boolean timedout = false;
6916
6917 synchronized(this) {
6918 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006919 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006920
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006921 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006922 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006923 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006924 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006925 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006926 long delay = endTime - System.currentTimeMillis();
6927 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006928 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006929 timedout = true;
6930 break;
6931 }
6932 try {
6933 this.wait();
6934 } catch (InterruptedException e) {
6935 }
6936 }
6937 }
6938 }
6939
6940 mUsageStatsService.shutdown();
6941 mBatteryStatsService.shutdown();
6942
6943 return timedout;
6944 }
6945
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006946 public final void activitySlept(IBinder token) {
6947 if (localLOGV) Slog.v(
6948 TAG, "Activity slept: token=" + token);
6949
6950 ActivityRecord r = null;
6951
6952 final long origId = Binder.clearCallingIdentity();
6953
6954 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006955 r = mMainStack.isInStackLocked(token);
6956 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006957 mMainStack.activitySleptLocked(r);
6958 }
6959 }
6960
6961 Binder.restoreCallingIdentity(origId);
6962 }
6963
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006964 private void comeOutOfSleepIfNeededLocked() {
6965 if (!mWentToSleep && !mLockScreenShown) {
6966 if (mSleeping) {
6967 mSleeping = false;
6968 mMainStack.awakeFromSleepingLocked();
6969 mMainStack.resumeTopActivityLocked(null);
6970 }
6971 }
6972 }
6973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006974 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006975 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6976 != PackageManager.PERMISSION_GRANTED) {
6977 throw new SecurityException("Requires permission "
6978 + android.Manifest.permission.DEVICE_POWER);
6979 }
6980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006981 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006982 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07006983 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006984 comeOutOfSleepIfNeededLocked();
6985 }
6986 }
6987
Jeff Brownc042ee22012-05-08 13:03:42 -07006988 private void updateEventDispatchingLocked() {
6989 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
6990 }
6991
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006992 public void setLockScreenShown(boolean shown) {
6993 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6994 != PackageManager.PERMISSION_GRANTED) {
6995 throw new SecurityException("Requires permission "
6996 + android.Manifest.permission.DEVICE_POWER);
6997 }
6998
6999 synchronized(this) {
7000 mLockScreenShown = shown;
7001 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007002 }
7003 }
7004
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007005 public void stopAppSwitches() {
7006 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7007 != PackageManager.PERMISSION_GRANTED) {
7008 throw new SecurityException("Requires permission "
7009 + android.Manifest.permission.STOP_APP_SWITCHES);
7010 }
7011
7012 synchronized(this) {
7013 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7014 + APP_SWITCH_DELAY_TIME;
7015 mDidAppSwitch = false;
7016 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7017 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7018 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7019 }
7020 }
7021
7022 public void resumeAppSwitches() {
7023 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7024 != PackageManager.PERMISSION_GRANTED) {
7025 throw new SecurityException("Requires permission "
7026 + android.Manifest.permission.STOP_APP_SWITCHES);
7027 }
7028
7029 synchronized(this) {
7030 // Note that we don't execute any pending app switches... we will
7031 // let those wait until either the timeout, or the next start
7032 // activity request.
7033 mAppSwitchesAllowedTime = 0;
7034 }
7035 }
7036
7037 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7038 String name) {
7039 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7040 return true;
7041 }
7042
7043 final int perm = checkComponentPermission(
7044 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007045 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007046 if (perm == PackageManager.PERMISSION_GRANTED) {
7047 return true;
7048 }
7049
Joe Onorato8a9b2202010-02-26 18:56:32 -08007050 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007051 return false;
7052 }
7053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007054 public void setDebugApp(String packageName, boolean waitForDebugger,
7055 boolean persistent) {
7056 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7057 "setDebugApp()");
7058
7059 // Note that this is not really thread safe if there are multiple
7060 // callers into it at the same time, but that's not a situation we
7061 // care about.
7062 if (persistent) {
7063 final ContentResolver resolver = mContext.getContentResolver();
7064 Settings.System.putString(
7065 resolver, Settings.System.DEBUG_APP,
7066 packageName);
7067 Settings.System.putInt(
7068 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7069 waitForDebugger ? 1 : 0);
7070 }
7071
7072 synchronized (this) {
7073 if (!persistent) {
7074 mOrigDebugApp = mDebugApp;
7075 mOrigWaitForDebugger = mWaitForDebugger;
7076 }
7077 mDebugApp = packageName;
7078 mWaitForDebugger = waitForDebugger;
7079 mDebugTransient = !persistent;
7080 if (packageName != null) {
7081 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07007082 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 Binder.restoreCallingIdentity(origId);
7084 }
7085 }
7086 }
7087
Siva Velusamy92a8b222012-03-09 16:24:04 -08007088 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7089 synchronized (this) {
7090 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7091 if (!isDebuggable) {
7092 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7093 throw new SecurityException("Process not debuggable: " + app.packageName);
7094 }
7095 }
7096
7097 mOpenGlTraceApp = processName;
7098 }
7099 }
7100
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007101 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7102 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7103 synchronized (this) {
7104 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7105 if (!isDebuggable) {
7106 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7107 throw new SecurityException("Process not debuggable: " + app.packageName);
7108 }
7109 }
7110 mProfileApp = processName;
7111 mProfileFile = profileFile;
7112 if (mProfileFd != null) {
7113 try {
7114 mProfileFd.close();
7115 } catch (IOException e) {
7116 }
7117 mProfileFd = null;
7118 }
7119 mProfileFd = profileFd;
7120 mProfileType = 0;
7121 mAutoStopProfiler = autoStopProfiler;
7122 }
7123 }
7124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007125 public void setAlwaysFinish(boolean enabled) {
7126 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7127 "setAlwaysFinish()");
7128
7129 Settings.System.putInt(
7130 mContext.getContentResolver(),
7131 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7132
7133 synchronized (this) {
7134 mAlwaysFinishActivities = enabled;
7135 }
7136 }
7137
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007138 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007139 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007140 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007141 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007142 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007143 }
7144 }
7145
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007146 public boolean isUserAMonkey() {
7147 // For now the fact that there is a controller implies
7148 // we have a monkey.
7149 synchronized (this) {
7150 return mController != null;
7151 }
7152 }
7153
Jeff Sharkeya4620792011-05-20 15:29:23 -07007154 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007155 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7156 "registerProcessObserver()");
7157 synchronized (this) {
7158 mProcessObservers.register(observer);
7159 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007160 }
7161
7162 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007163 synchronized (this) {
7164 mProcessObservers.unregister(observer);
7165 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007166 }
7167
Daniel Sandler69a48172010-06-23 16:29:36 -04007168 public void setImmersive(IBinder token, boolean immersive) {
7169 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007170 ActivityRecord r = mMainStack.isInStackLocked(token);
7171 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007172 throw new IllegalArgumentException();
7173 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007174 r.immersive = immersive;
7175 }
7176 }
7177
7178 public boolean isImmersive(IBinder token) {
7179 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007180 ActivityRecord r = mMainStack.isInStackLocked(token);
7181 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007182 throw new IllegalArgumentException();
7183 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007184 return r.immersive;
7185 }
7186 }
7187
7188 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007189 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007190 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007191 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007192 return (r != null) ? r.immersive : false;
7193 }
7194 }
7195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 public final void enterSafeMode() {
7197 synchronized(this) {
7198 // It only makes sense to do this before the system is ready
7199 // and started launching other packages.
7200 if (!mSystemReady) {
7201 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007202 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007203 } catch (RemoteException e) {
7204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 }
7206 }
7207 }
7208
Jeff Brownb09abc12011-01-13 21:08:27 -08007209 public final void showSafeModeOverlay() {
7210 View v = LayoutInflater.from(mContext).inflate(
7211 com.android.internal.R.layout.safe_mode, null);
7212 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7213 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7214 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7215 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007216 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007217 lp.format = v.getBackground().getOpacity();
7218 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7219 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7220 ((WindowManager)mContext.getSystemService(
7221 Context.WINDOW_SERVICE)).addView(v, lp);
7222 }
7223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 public void noteWakeupAlarm(IIntentSender sender) {
7225 if (!(sender instanceof PendingIntentRecord)) {
7226 return;
7227 }
7228 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7229 synchronized (stats) {
7230 if (mBatteryStatsService.isOnBattery()) {
7231 mBatteryStatsService.enforceCallingPermission();
7232 PendingIntentRecord rec = (PendingIntentRecord)sender;
7233 int MY_UID = Binder.getCallingUid();
7234 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7235 BatteryStatsImpl.Uid.Pkg pkg =
7236 stats.getPackageStatsLocked(uid, rec.key.packageName);
7237 pkg.incWakeupsLocked();
7238 }
7239 }
7240 }
7241
Dianne Hackborn64825172011-03-02 21:32:58 -08007242 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007243 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007244 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007245 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007246 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007247 // XXX Note: don't acquire main activity lock here, because the window
7248 // manager calls in with its locks held.
7249
7250 boolean killed = false;
7251 synchronized (mPidsSelfLocked) {
7252 int[] types = new int[pids.length];
7253 int worstType = 0;
7254 for (int i=0; i<pids.length; i++) {
7255 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7256 if (proc != null) {
7257 int type = proc.setAdj;
7258 types[i] = type;
7259 if (type > worstType) {
7260 worstType = type;
7261 }
7262 }
7263 }
7264
Dianne Hackborn64825172011-03-02 21:32:58 -08007265 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007266 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007267 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7268 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007269 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007270 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007271
7272 // If this is not a secure call, don't let it kill processes that
7273 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007274 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7275 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007276 }
7277
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007278 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007279 for (int i=0; i<pids.length; i++) {
7280 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7281 if (proc == null) {
7282 continue;
7283 }
7284 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007285 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007286 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007287 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7288 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007289 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007290 proc.killedBackground = true;
7291 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007292 }
7293 }
7294 }
7295 return killed;
7296 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007297
7298 @Override
7299 public boolean killProcessesBelowForeground(String reason) {
7300 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7301 throw new SecurityException("killProcessesBelowForeground() only available to system");
7302 }
7303
7304 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7305 }
7306
7307 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7308 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7309 throw new SecurityException("killProcessesBelowAdj() only available to system");
7310 }
7311
7312 boolean killed = false;
7313 synchronized (mPidsSelfLocked) {
7314 final int size = mPidsSelfLocked.size();
7315 for (int i = 0; i < size; i++) {
7316 final int pid = mPidsSelfLocked.keyAt(i);
7317 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7318 if (proc == null) continue;
7319
7320 final int adj = proc.setAdj;
7321 if (adj > belowAdj && !proc.killedBackground) {
7322 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7323 EventLog.writeEvent(
7324 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7325 killed = true;
7326 proc.killedBackground = true;
7327 Process.killProcessQuiet(pid);
7328 }
7329 }
7330 }
7331 return killed;
7332 }
7333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 public final void startRunning(String pkg, String cls, String action,
7335 String data) {
7336 synchronized(this) {
7337 if (mStartRunning) {
7338 return;
7339 }
7340 mStartRunning = true;
7341 mTopComponent = pkg != null && cls != null
7342 ? new ComponentName(pkg, cls) : null;
7343 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7344 mTopData = data;
7345 if (!mSystemReady) {
7346 return;
7347 }
7348 }
7349
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007350 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 }
7352
7353 private void retrieveSettings() {
7354 final ContentResolver resolver = mContext.getContentResolver();
7355 String debugApp = Settings.System.getString(
7356 resolver, Settings.System.DEBUG_APP);
7357 boolean waitForDebugger = Settings.System.getInt(
7358 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7359 boolean alwaysFinishActivities = Settings.System.getInt(
7360 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7361
7362 Configuration configuration = new Configuration();
7363 Settings.System.getConfiguration(resolver, configuration);
7364
7365 synchronized (this) {
7366 mDebugApp = mOrigDebugApp = debugApp;
7367 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7368 mAlwaysFinishActivities = alwaysFinishActivities;
7369 // This happens before any activities are started, so we can
7370 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007371 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007372 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007373 }
7374 }
7375
7376 public boolean testIsSystemReady() {
7377 // no need to synchronize(this) just to read & return the value
7378 return mSystemReady;
7379 }
7380
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007381 private static File getCalledPreBootReceiversFile() {
7382 File dataDir = Environment.getDataDirectory();
7383 File systemDir = new File(dataDir, "system");
7384 File fname = new File(systemDir, "called_pre_boots.dat");
7385 return fname;
7386 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007387
7388 static final int LAST_DONE_VERSION = 10000;
7389
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007390 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7391 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7392 File file = getCalledPreBootReceiversFile();
7393 FileInputStream fis = null;
7394 try {
7395 fis = new FileInputStream(file);
7396 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007397 int fvers = dis.readInt();
7398 if (fvers == LAST_DONE_VERSION) {
7399 String vers = dis.readUTF();
7400 String codename = dis.readUTF();
7401 String build = dis.readUTF();
7402 if (android.os.Build.VERSION.RELEASE.equals(vers)
7403 && android.os.Build.VERSION.CODENAME.equals(codename)
7404 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7405 int num = dis.readInt();
7406 while (num > 0) {
7407 num--;
7408 String pkg = dis.readUTF();
7409 String cls = dis.readUTF();
7410 lastDoneReceivers.add(new ComponentName(pkg, cls));
7411 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007412 }
7413 }
7414 } catch (FileNotFoundException e) {
7415 } catch (IOException e) {
7416 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7417 } finally {
7418 if (fis != null) {
7419 try {
7420 fis.close();
7421 } catch (IOException e) {
7422 }
7423 }
7424 }
7425 return lastDoneReceivers;
7426 }
7427
7428 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7429 File file = getCalledPreBootReceiversFile();
7430 FileOutputStream fos = null;
7431 DataOutputStream dos = null;
7432 try {
7433 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7434 fos = new FileOutputStream(file);
7435 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007436 dos.writeInt(LAST_DONE_VERSION);
7437 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007438 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007439 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007440 dos.writeInt(list.size());
7441 for (int i=0; i<list.size(); i++) {
7442 dos.writeUTF(list.get(i).getPackageName());
7443 dos.writeUTF(list.get(i).getClassName());
7444 }
7445 } catch (IOException e) {
7446 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7447 file.delete();
7448 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007449 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007450 if (dos != null) {
7451 try {
7452 dos.close();
7453 } catch (IOException e) {
7454 // TODO Auto-generated catch block
7455 e.printStackTrace();
7456 }
7457 }
7458 }
7459 }
7460
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007461 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007462 synchronized(this) {
7463 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007464 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007465 return;
7466 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007467
7468 // Check to see if there are any update receivers to run.
7469 if (!mDidUpdate) {
7470 if (mWaitingUpdate) {
7471 return;
7472 }
7473 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7474 List<ResolveInfo> ris = null;
7475 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007476 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007477 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007478 } catch (RemoteException e) {
7479 }
7480 if (ris != null) {
7481 for (int i=ris.size()-1; i>=0; i--) {
7482 if ((ris.get(i).activityInfo.applicationInfo.flags
7483 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7484 ris.remove(i);
7485 }
7486 }
7487 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007488
7489 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7490
7491 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007492 for (int i=0; i<ris.size(); i++) {
7493 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007494 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7495 if (lastDoneReceivers.contains(comp)) {
7496 ris.remove(i);
7497 i--;
7498 }
7499 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007500
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007501 for (int i=0; i<ris.size(); i++) {
7502 ActivityInfo ai = ris.get(i).activityInfo;
7503 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7504 doneReceivers.add(comp);
7505 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007506 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007507 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007508 finisher = new IIntentReceiver.Stub() {
7509 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007510 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007511 boolean sticky) {
7512 // The raw IIntentReceiver interface is called
7513 // with the AM lock held, so redispatch to
7514 // execute our code without the lock.
7515 mHandler.post(new Runnable() {
7516 public void run() {
7517 synchronized (ActivityManagerService.this) {
7518 mDidUpdate = true;
7519 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007520 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007521 showBootMessage(mContext.getText(
7522 R.string.android_upgrading_complete),
7523 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007524 systemReady(goingCallback);
7525 }
7526 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007527 }
7528 };
7529 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007530 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007531 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007532 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007533 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007534 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007535 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007536 mWaitingUpdate = true;
7537 }
7538 }
7539 }
7540 if (mWaitingUpdate) {
7541 return;
7542 }
7543 mDidUpdate = true;
7544 }
7545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007546 mSystemReady = true;
7547 if (!mStartRunning) {
7548 return;
7549 }
7550 }
7551
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007552 ArrayList<ProcessRecord> procsToKill = null;
7553 synchronized(mPidsSelfLocked) {
7554 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7555 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7556 if (!isAllowedWhileBooting(proc.info)){
7557 if (procsToKill == null) {
7558 procsToKill = new ArrayList<ProcessRecord>();
7559 }
7560 procsToKill.add(proc);
7561 }
7562 }
7563 }
7564
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007565 synchronized(this) {
7566 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007567 for (int i=procsToKill.size()-1; i>=0; i--) {
7568 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007569 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007570 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007571 }
7572 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007573
7574 // Now that we have cleaned up any update processes, we
7575 // are ready to start launching real processes and know that
7576 // we won't trample on them any more.
7577 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007578 }
7579
Joe Onorato8a9b2202010-02-26 18:56:32 -08007580 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007581 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582 SystemClock.uptimeMillis());
7583
7584 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007585 // Make sure we have no pre-ready processes sitting around.
7586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7588 ResolveInfo ri = mContext.getPackageManager()
7589 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007590 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007591 CharSequence errorMsg = null;
7592 if (ri != null) {
7593 ActivityInfo ai = ri.activityInfo;
7594 ApplicationInfo app = ai.applicationInfo;
7595 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7596 mTopAction = Intent.ACTION_FACTORY_TEST;
7597 mTopData = null;
7598 mTopComponent = new ComponentName(app.packageName,
7599 ai.name);
7600 } else {
7601 errorMsg = mContext.getResources().getText(
7602 com.android.internal.R.string.factorytest_not_system);
7603 }
7604 } else {
7605 errorMsg = mContext.getResources().getText(
7606 com.android.internal.R.string.factorytest_no_action);
7607 }
7608 if (errorMsg != null) {
7609 mTopAction = null;
7610 mTopData = null;
7611 mTopComponent = null;
7612 Message msg = Message.obtain();
7613 msg.what = SHOW_FACTORY_ERROR_MSG;
7614 msg.getData().putCharSequence("msg", errorMsg);
7615 mHandler.sendMessage(msg);
7616 }
7617 }
7618 }
7619
7620 retrieveSettings();
7621
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007622 if (goingCallback != null) goingCallback.run();
7623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007624 synchronized (this) {
7625 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7626 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007627 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007628 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007629 if (apps != null) {
7630 int N = apps.size();
7631 int i;
7632 for (i=0; i<N; i++) {
7633 ApplicationInfo info
7634 = (ApplicationInfo)apps.get(i);
7635 if (info != null &&
7636 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007637 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007638 }
7639 }
7640 }
7641 } catch (RemoteException ex) {
7642 // pm is in same process, this will never happen.
7643 }
7644 }
7645
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007646 // Start up initial activity.
7647 mBooting = true;
7648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007650 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007651 Message msg = Message.obtain();
7652 msg.what = SHOW_UID_ERROR_MSG;
7653 mHandler.sendMessage(msg);
7654 }
7655 } catch (RemoteException e) {
7656 }
7657
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007658 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007659 }
7660 }
7661
Dan Egnorb7f03672009-12-09 16:22:32 -08007662 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007663 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007664 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007665 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007666 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667 startAppProblemLocked(app);
7668 app.stopFreezingAllLocked();
7669 return handleAppCrashLocked(app);
7670 }
7671
Dan Egnorb7f03672009-12-09 16:22:32 -08007672 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007673 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007674 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007675 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007676 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7677 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 startAppProblemLocked(app);
7679 app.stopFreezingAllLocked();
7680 }
7681
7682 /**
7683 * Generate a process error record, suitable for attachment to a ProcessRecord.
7684 *
7685 * @param app The ProcessRecord in which the error occurred.
7686 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7687 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007688 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007689 * @param shortMsg Short message describing the crash.
7690 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007691 * @param stackTrace Full crash stack trace, may be null.
7692 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007693 * @return Returns a fully-formed AppErrorStateInfo record.
7694 */
7695 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007696 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007697 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007699 report.condition = condition;
7700 report.processName = app.processName;
7701 report.pid = app.pid;
7702 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007703 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007704 report.shortMsg = shortMsg;
7705 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007706 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707
7708 return report;
7709 }
7710
Dan Egnor42471dd2010-01-07 17:25:22 -08007711 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 synchronized (this) {
7713 app.crashing = false;
7714 app.crashingReport = null;
7715 app.notResponding = false;
7716 app.notRespondingReport = null;
7717 if (app.anrDialog == fromDialog) {
7718 app.anrDialog = null;
7719 }
7720 if (app.waitDialog == fromDialog) {
7721 app.waitDialog = null;
7722 }
7723 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007724 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007725 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007726 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7727 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007728 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 }
7731 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007732
Dan Egnorb7f03672009-12-09 16:22:32 -08007733 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007734 if (mHeadless) {
7735 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7736 return false;
7737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 long now = SystemClock.uptimeMillis();
7739
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007740 Long crashTime;
7741 if (!app.isolated) {
7742 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7743 } else {
7744 crashTime = null;
7745 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007746 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007748 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007749 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007750 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007751 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007752 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7753 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007754 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007755 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007756 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007757 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007758 }
7759 }
7760 if (!app.persistent) {
7761 // We don't want to start this process again until the user
7762 // explicitly does so... but for persistent process, we really
7763 // need to keep it running. If a persistent process is actually
7764 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007765 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007766 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007767 if (!app.isolated) {
7768 // XXX We don't have a way to mark isolated processes
7769 // as bad, since they don't have a peristent identity.
7770 mBadProcesses.put(app.info.processName, app.uid, now);
7771 mProcessCrashTimes.remove(app.info.processName, app.uid);
7772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007774 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007775 // Don't let services in this process be restarted and potentially
7776 // annoy the user repeatedly. Unless it is persistent, since those
7777 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007778 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007779 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 return false;
7781 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007782 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007783 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007784 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007785 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007786 // If the top running activity is from this crashing
7787 // process, then terminate it to avoid getting in a loop.
7788 Slog.w(TAG, " Force finishing activity "
7789 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007790 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007791 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007792 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007793 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007794 // stopped, to avoid a situation where one will get
7795 // re-start our crashing activity once it gets resumed again.
7796 index--;
7797 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007798 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007799 if (r.state == ActivityState.RESUMED
7800 || r.state == ActivityState.PAUSING
7801 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007802 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007803 Slog.w(TAG, " Force finishing activity "
7804 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007805 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007806 Activity.RESULT_CANCELED, null, "crashed");
7807 }
7808 }
7809 }
7810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007811 }
7812
7813 // Bump up the crash count of any services currently running in the proc.
7814 if (app.services.size() != 0) {
7815 // Any services running in the application need to be placed
7816 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007817 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007819 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007820 sr.crashCount++;
7821 }
7822 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007823
7824 // If the crashing process is what we consider to be the "home process" and it has been
7825 // replaced by a third-party app, clear the package preferred activities from packages
7826 // with a home activity running in the process to prevent a repeatedly crashing app
7827 // from blocking the user to manually clear the list.
7828 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7829 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7830 Iterator it = mHomeProcess.activities.iterator();
7831 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007832 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007833 if (r.isHomeActivity) {
7834 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7835 try {
7836 ActivityThread.getPackageManager()
7837 .clearPackagePreferredActivities(r.packageName);
7838 } catch (RemoteException c) {
7839 // pm is in same process, this will never happen.
7840 }
7841 }
7842 }
7843 }
7844
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007845 if (!app.isolated) {
7846 // XXX Can't keep track of crash times for isolated processes,
7847 // because they don't have a perisistent identity.
7848 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7849 }
7850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 return true;
7852 }
7853
7854 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007855 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7856 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 skipCurrentReceiverLocked(app);
7858 }
7859
7860 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007861 for (BroadcastQueue queue : mBroadcastQueues) {
7862 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007863 }
7864 }
7865
Dan Egnor60d87622009-12-16 16:32:58 -08007866 /**
7867 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7868 * The application process will exit immediately after this call returns.
7869 * @param app object of the crashing app, null for the system server
7870 * @param crashInfo describing the exception
7871 */
7872 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007873 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007874 final String processName = app == null ? "system_server"
7875 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007876
7877 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007878 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007879 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007880 crashInfo.exceptionClassName,
7881 crashInfo.exceptionMessage,
7882 crashInfo.throwFileName,
7883 crashInfo.throwLineNumber);
7884
Jeff Sharkeya353d262011-10-28 11:12:06 -07007885 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007886
7887 crashApplication(r, crashInfo);
7888 }
7889
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007890 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007891 IBinder app,
7892 int violationMask,
7893 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007894 ProcessRecord r = findAppProcess(app, "StrictMode");
7895 if (r == null) {
7896 return;
7897 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007898
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007899 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007900 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007901 boolean logIt = true;
7902 synchronized (mAlreadyLoggedViolatedStacks) {
7903 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7904 logIt = false;
7905 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007906 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007907 // the relative pain numbers, without logging all
7908 // the stack traces repeatedly. We'd want to do
7909 // likewise in the client code, which also does
7910 // dup suppression, before the Binder call.
7911 } else {
7912 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7913 mAlreadyLoggedViolatedStacks.clear();
7914 }
7915 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7916 }
7917 }
7918 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007919 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007920 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007921 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007922
7923 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7924 AppErrorResult result = new AppErrorResult();
7925 synchronized (this) {
7926 final long origId = Binder.clearCallingIdentity();
7927
7928 Message msg = Message.obtain();
7929 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7930 HashMap<String, Object> data = new HashMap<String, Object>();
7931 data.put("result", result);
7932 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007933 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007934 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007935 msg.obj = data;
7936 mHandler.sendMessage(msg);
7937
7938 Binder.restoreCallingIdentity(origId);
7939 }
7940 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007941 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007942 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007943 }
7944
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007945 // Depending on the policy in effect, there could be a bunch of
7946 // these in quick succession so we try to batch these together to
7947 // minimize disk writes, number of dropbox entries, and maximize
7948 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007949 private void logStrictModeViolationToDropBox(
7950 ProcessRecord process,
7951 StrictMode.ViolationInfo info) {
7952 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007953 return;
7954 }
7955 final boolean isSystemApp = process == null ||
7956 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7957 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007958 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007959 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7960 final DropBoxManager dbox = (DropBoxManager)
7961 mContext.getSystemService(Context.DROPBOX_SERVICE);
7962
7963 // Exit early if the dropbox isn't configured to accept this report type.
7964 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7965
7966 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007967 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007968 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7969 synchronized (sb) {
7970 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007971 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007972 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7973 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007974 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7975 if (info.violationNumThisLoop != 0) {
7976 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7977 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007978 if (info.numAnimationsRunning != 0) {
7979 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7980 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007981 if (info.broadcastIntentAction != null) {
7982 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7983 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007984 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007985 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007986 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007987 if (info.numInstances != -1) {
7988 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7989 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007990 if (info.tags != null) {
7991 for (String tag : info.tags) {
7992 sb.append("Span-Tag: ").append(tag).append("\n");
7993 }
7994 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007995 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007996 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7997 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007998 }
7999 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008000
8001 // Only buffer up to ~64k. Various logging bits truncate
8002 // things at 128k.
8003 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008004 }
8005
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008006 // Flush immediately if the buffer's grown too large, or this
8007 // is a non-system app. Non-system apps are isolated with a
8008 // different tag & policy and not batched.
8009 //
8010 // Batching is useful during internal testing with
8011 // StrictMode settings turned up high. Without batching,
8012 // thousands of separate files could be created on boot.
8013 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008014 new Thread("Error dump: " + dropboxTag) {
8015 @Override
8016 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008017 String report;
8018 synchronized (sb) {
8019 report = sb.toString();
8020 sb.delete(0, sb.length());
8021 sb.trimToSize();
8022 }
8023 if (report.length() != 0) {
8024 dbox.addText(dropboxTag, report);
8025 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008026 }
8027 }.start();
8028 return;
8029 }
8030
8031 // System app batching:
8032 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008033 // An existing dropbox-writing thread is outstanding, so
8034 // we don't need to start it up. The existing thread will
8035 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008036 return;
8037 }
8038
8039 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8040 // (After this point, we shouldn't access AMS internal data structures.)
8041 new Thread("Error dump: " + dropboxTag) {
8042 @Override
8043 public void run() {
8044 // 5 second sleep to let stacks arrive and be batched together
8045 try {
8046 Thread.sleep(5000); // 5 seconds
8047 } catch (InterruptedException e) {}
8048
8049 String errorReport;
8050 synchronized (mStrictModeBuffer) {
8051 errorReport = mStrictModeBuffer.toString();
8052 if (errorReport.length() == 0) {
8053 return;
8054 }
8055 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8056 mStrictModeBuffer.trimToSize();
8057 }
8058 dbox.addText(dropboxTag, errorReport);
8059 }
8060 }.start();
8061 }
8062
Dan Egnor60d87622009-12-16 16:32:58 -08008063 /**
8064 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8065 * @param app object of the crashing app, null for the system server
8066 * @param tag reported by the caller
8067 * @param crashInfo describing the context of the error
8068 * @return true if the process should exit immediately (WTF is fatal)
8069 */
8070 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008071 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008072 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008073 final String processName = app == null ? "system_server"
8074 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008075
8076 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008077 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008078 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008079 tag, crashInfo.exceptionMessage);
8080
Jeff Sharkeya353d262011-10-28 11:12:06 -07008081 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008082
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008083 if (r != null && r.pid != Process.myPid() &&
8084 Settings.Secure.getInt(mContext.getContentResolver(),
8085 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008086 crashApplication(r, crashInfo);
8087 return true;
8088 } else {
8089 return false;
8090 }
8091 }
8092
8093 /**
8094 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8095 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8096 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008097 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008098 if (app == null) {
8099 return null;
8100 }
8101
8102 synchronized (this) {
8103 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8104 final int NA = apps.size();
8105 for (int ia=0; ia<NA; ia++) {
8106 ProcessRecord p = apps.valueAt(ia);
8107 if (p.thread != null && p.thread.asBinder() == app) {
8108 return p;
8109 }
8110 }
8111 }
8112
Dianne Hackborncb44d962011-03-10 17:02:27 -08008113 Slog.w(TAG, "Can't find mystery application for " + reason
8114 + " from pid=" + Binder.getCallingPid()
8115 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008116 return null;
8117 }
8118 }
8119
8120 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008121 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8122 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008123 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008124 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8125 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008126 // Watchdog thread ends up invoking this function (with
8127 // a null ProcessRecord) to add the stack file to dropbox.
8128 // Do not acquire a lock on this (am) in such cases, as it
8129 // could cause a potential deadlock, if and when watchdog
8130 // is invoked due to unavailability of lock on am and it
8131 // would prevent watchdog from killing system_server.
8132 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008133 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008134 return;
8135 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008136 // Note: ProcessRecord 'process' is guarded by the service
8137 // instance. (notably process.pkgList, which could otherwise change
8138 // concurrently during execution of this method)
8139 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008140 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008141 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008142 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008143 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8144 for (String pkg : process.pkgList) {
8145 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008146 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008147 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008148 if (pi != null) {
8149 sb.append(" v").append(pi.versionCode);
8150 if (pi.versionName != null) {
8151 sb.append(" (").append(pi.versionName).append(")");
8152 }
8153 }
8154 } catch (RemoteException e) {
8155 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008156 }
Dan Egnora455d192010-03-12 08:52:28 -08008157 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008158 }
Dan Egnora455d192010-03-12 08:52:28 -08008159 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008160 }
8161
8162 private static String processClass(ProcessRecord process) {
8163 if (process == null || process.pid == MY_PID) {
8164 return "system_server";
8165 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8166 return "system_app";
8167 } else {
8168 return "data_app";
8169 }
8170 }
8171
8172 /**
8173 * Write a description of an error (crash, WTF, ANR) to the drop box.
8174 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8175 * @param process which caused the error, null means the system server
8176 * @param activity which triggered the error, null if unknown
8177 * @param parent activity related to the error, null if unknown
8178 * @param subject line related to the error, null if absent
8179 * @param report in long form describing the error, null if absent
8180 * @param logFile to include in the report, null if none
8181 * @param crashInfo giving an application stack trace, null if absent
8182 */
8183 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008184 ProcessRecord process, String processName, ActivityRecord activity,
8185 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008186 final String report, final File logFile,
8187 final ApplicationErrorReport.CrashInfo crashInfo) {
8188 // NOTE -- this must never acquire the ActivityManagerService lock,
8189 // otherwise the watchdog may be prevented from resetting the system.
8190
8191 final String dropboxTag = processClass(process) + "_" + eventType;
8192 final DropBoxManager dbox = (DropBoxManager)
8193 mContext.getSystemService(Context.DROPBOX_SERVICE);
8194
8195 // Exit early if the dropbox isn't configured to accept this report type.
8196 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8197
8198 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008199 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008200 if (activity != null) {
8201 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8202 }
8203 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8204 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8205 }
8206 if (parent != null && parent != activity) {
8207 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8208 }
8209 if (subject != null) {
8210 sb.append("Subject: ").append(subject).append("\n");
8211 }
8212 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008213 if (Debug.isDebuggerConnected()) {
8214 sb.append("Debugger: Connected\n");
8215 }
Dan Egnora455d192010-03-12 08:52:28 -08008216 sb.append("\n");
8217
8218 // Do the rest in a worker thread to avoid blocking the caller on I/O
8219 // (After this point, we shouldn't access AMS internal data structures.)
8220 Thread worker = new Thread("Error dump: " + dropboxTag) {
8221 @Override
8222 public void run() {
8223 if (report != null) {
8224 sb.append(report);
8225 }
8226 if (logFile != null) {
8227 try {
8228 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8229 } catch (IOException e) {
8230 Slog.e(TAG, "Error reading " + logFile, e);
8231 }
8232 }
8233 if (crashInfo != null && crashInfo.stackTrace != null) {
8234 sb.append(crashInfo.stackTrace);
8235 }
8236
8237 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8238 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8239 if (lines > 0) {
8240 sb.append("\n");
8241
8242 // Merge several logcat streams, and take the last N lines
8243 InputStreamReader input = null;
8244 try {
8245 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8246 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8247 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8248
8249 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8250 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8251 input = new InputStreamReader(logcat.getInputStream());
8252
8253 int num;
8254 char[] buf = new char[8192];
8255 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8256 } catch (IOException e) {
8257 Slog.e(TAG, "Error running logcat", e);
8258 } finally {
8259 if (input != null) try { input.close(); } catch (IOException e) {}
8260 }
8261 }
8262
8263 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008264 }
Dan Egnora455d192010-03-12 08:52:28 -08008265 };
8266
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008267 if (process == null) {
8268 // If process is null, we are being called from some internal code
8269 // and may be about to die -- run this synchronously.
8270 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008271 } else {
8272 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008273 }
8274 }
8275
8276 /**
8277 * Bring up the "unexpected error" dialog box for a crashing app.
8278 * Deal with edge cases (intercepts from instrumented applications,
8279 * ActivityController, error intent receivers, that sort of thing).
8280 * @param r the application crashing
8281 * @param crashInfo describing the failure
8282 */
8283 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008284 long timeMillis = System.currentTimeMillis();
8285 String shortMsg = crashInfo.exceptionClassName;
8286 String longMsg = crashInfo.exceptionMessage;
8287 String stackTrace = crashInfo.stackTrace;
8288 if (shortMsg != null && longMsg != null) {
8289 longMsg = shortMsg + ": " + longMsg;
8290 } else if (shortMsg != null) {
8291 longMsg = shortMsg;
8292 }
8293
Dan Egnor60d87622009-12-16 16:32:58 -08008294 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008295 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008296 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008297 try {
8298 String name = r != null ? r.processName : null;
8299 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008300 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008301 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008302 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008303 + " at watcher's request");
8304 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008305 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008306 }
8307 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008308 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008309 }
8310 }
8311
8312 final long origId = Binder.clearCallingIdentity();
8313
8314 // If this process is running instrumentation, finish it.
8315 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008316 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008317 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008318 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8319 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008320 Bundle info = new Bundle();
8321 info.putString("shortMsg", shortMsg);
8322 info.putString("longMsg", longMsg);
8323 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8324 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008325 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008326 }
8327
Dan Egnor60d87622009-12-16 16:32:58 -08008328 // If we can't identify the process or it's already exceeded its crash quota,
8329 // quit right away without showing a crash dialog.
8330 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008331 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008332 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008333 }
8334
8335 Message msg = Message.obtain();
8336 msg.what = SHOW_ERROR_MSG;
8337 HashMap data = new HashMap();
8338 data.put("result", result);
8339 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008340 msg.obj = data;
8341 mHandler.sendMessage(msg);
8342
8343 Binder.restoreCallingIdentity(origId);
8344 }
8345
8346 int res = result.get();
8347
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008348 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008349 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008350 if (r != null && !r.isolated) {
8351 // XXX Can't keep track of crash time for isolated processes,
8352 // since they don't have a persistent identity.
8353 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008354 SystemClock.uptimeMillis());
8355 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008356 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008357 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008358 }
8359 }
8360
8361 if (appErrorIntent != null) {
8362 try {
8363 mContext.startActivity(appErrorIntent);
8364 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008365 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008368 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008369
8370 Intent createAppErrorIntentLocked(ProcessRecord r,
8371 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8372 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008373 if (report == null) {
8374 return null;
8375 }
8376 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8377 result.setComponent(r.errorReportReceiver);
8378 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8379 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8380 return result;
8381 }
8382
Dan Egnorb7f03672009-12-09 16:22:32 -08008383 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8384 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008385 if (r.errorReportReceiver == null) {
8386 return null;
8387 }
8388
8389 if (!r.crashing && !r.notResponding) {
8390 return null;
8391 }
8392
Dan Egnorb7f03672009-12-09 16:22:32 -08008393 ApplicationErrorReport report = new ApplicationErrorReport();
8394 report.packageName = r.info.packageName;
8395 report.installerPackageName = r.errorReportReceiver.getPackageName();
8396 report.processName = r.processName;
8397 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008398 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008399
Dan Egnorb7f03672009-12-09 16:22:32 -08008400 if (r.crashing) {
8401 report.type = ApplicationErrorReport.TYPE_CRASH;
8402 report.crashInfo = crashInfo;
8403 } else if (r.notResponding) {
8404 report.type = ApplicationErrorReport.TYPE_ANR;
8405 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008406
Dan Egnorb7f03672009-12-09 16:22:32 -08008407 report.anrInfo.activity = r.notRespondingReport.tag;
8408 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8409 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008410 }
8411
Dan Egnorb7f03672009-12-09 16:22:32 -08008412 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008413 }
8414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008415 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008416 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008417 // assume our apps are happy - lazy create the list
8418 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8419
8420 synchronized (this) {
8421
8422 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008423 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8424 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008425 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8426 // This one's in trouble, so we'll generate a report for it
8427 // crashes are higher priority (in case there's a crash *and* an anr)
8428 ActivityManager.ProcessErrorStateInfo report = null;
8429 if (app.crashing) {
8430 report = app.crashingReport;
8431 } else if (app.notResponding) {
8432 report = app.notRespondingReport;
8433 }
8434
8435 if (report != null) {
8436 if (errList == null) {
8437 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8438 }
8439 errList.add(report);
8440 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008441 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008442 " crashing = " + app.crashing +
8443 " notResponding = " + app.notResponding);
8444 }
8445 }
8446 }
8447 }
8448
8449 return errList;
8450 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008451
8452 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008453 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008454 if (currApp != null) {
8455 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8456 }
8457 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008458 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8459 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008460 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8461 if (currApp != null) {
8462 currApp.lru = 0;
8463 }
8464 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008465 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008466 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8467 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8468 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8469 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8470 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8471 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8472 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8473 } else {
8474 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8475 }
8476 }
8477
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008478 private void fillInProcMemInfo(ProcessRecord app,
8479 ActivityManager.RunningAppProcessInfo outInfo) {
8480 outInfo.pid = app.pid;
8481 outInfo.uid = app.info.uid;
8482 if (mHeavyWeightProcess == app) {
8483 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8484 }
8485 if (app.persistent) {
8486 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8487 }
8488 outInfo.lastTrimLevel = app.trimMemoryLevel;
8489 int adj = app.curAdj;
8490 outInfo.importance = oomAdjToImportance(adj, outInfo);
8491 outInfo.importanceReasonCode = app.adjTypeCode;
8492 }
8493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008495 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008496 // Lazy instantiation of list
8497 List<ActivityManager.RunningAppProcessInfo> runList = null;
8498 synchronized (this) {
8499 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008500 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8501 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8503 // Generate process state info for running application
8504 ActivityManager.RunningAppProcessInfo currApp =
8505 new ActivityManager.RunningAppProcessInfo(app.processName,
8506 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008507 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008508 if (app.adjSource instanceof ProcessRecord) {
8509 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008510 currApp.importanceReasonImportance = oomAdjToImportance(
8511 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008512 } else if (app.adjSource instanceof ActivityRecord) {
8513 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008514 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8515 }
8516 if (app.adjTarget instanceof ComponentName) {
8517 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8518 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008519 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008520 // + " lru=" + currApp.lru);
8521 if (runList == null) {
8522 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8523 }
8524 runList.add(currApp);
8525 }
8526 }
8527 }
8528 return runList;
8529 }
8530
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008531 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008532 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008533 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8534 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8535 if (runningApps != null && runningApps.size() > 0) {
8536 Set<String> extList = new HashSet<String>();
8537 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8538 if (app.pkgList != null) {
8539 for (String pkg : app.pkgList) {
8540 extList.add(pkg);
8541 }
8542 }
8543 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008544 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008545 for (String pkg : extList) {
8546 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008547 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008548 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8549 retList.add(info);
8550 }
8551 } catch (RemoteException e) {
8552 }
8553 }
8554 }
8555 return retList;
8556 }
8557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008558 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008559 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8560 enforceNotIsolatedCaller("getMyMemoryState");
8561 synchronized (this) {
8562 ProcessRecord proc;
8563 synchronized (mPidsSelfLocked) {
8564 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8565 }
8566 fillInProcMemInfo(proc, outInfo);
8567 }
8568 }
8569
8570 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008571 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008572 if (checkCallingPermission(android.Manifest.permission.DUMP)
8573 != PackageManager.PERMISSION_GRANTED) {
8574 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8575 + Binder.getCallingPid()
8576 + ", uid=" + Binder.getCallingUid()
8577 + " without permission "
8578 + android.Manifest.permission.DUMP);
8579 return;
8580 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008581
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008582 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008583 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008584 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008585
8586 int opti = 0;
8587 while (opti < args.length) {
8588 String opt = args[opti];
8589 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8590 break;
8591 }
8592 opti++;
8593 if ("-a".equals(opt)) {
8594 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008595 } else if ("-c".equals(opt)) {
8596 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008597 } else if ("-h".equals(opt)) {
8598 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008599 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008600 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008601 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008602 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8603 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8604 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008605 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008606 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008607 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008608 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008609 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008610 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008611 pw.println(" all: dump all activities");
8612 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008613 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008614 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8615 pw.println(" a partial substring in a component name, a");
8616 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008617 pw.println(" -a: include all available server state.");
8618 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008619 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008620 } else {
8621 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008623 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008624
8625 long origId = Binder.clearCallingIdentity();
8626 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008627 // Is the caller requesting to dump a particular piece of data?
8628 if (opti < args.length) {
8629 String cmd = args[opti];
8630 opti++;
8631 if ("activities".equals(cmd) || "a".equals(cmd)) {
8632 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008633 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008635 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008636 String[] newArgs;
8637 String name;
8638 if (opti >= args.length) {
8639 name = null;
8640 newArgs = EMPTY_STRING_ARRAY;
8641 } else {
8642 name = args[opti];
8643 opti++;
8644 newArgs = new String[args.length - opti];
8645 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8646 args.length - opti);
8647 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008648 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008649 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008650 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008651 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008652 String[] newArgs;
8653 String name;
8654 if (opti >= args.length) {
8655 name = null;
8656 newArgs = EMPTY_STRING_ARRAY;
8657 } else {
8658 name = args[opti];
8659 opti++;
8660 newArgs = new String[args.length - opti];
8661 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8662 args.length - opti);
8663 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008664 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008665 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008666 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008667 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008668 String[] newArgs;
8669 String name;
8670 if (opti >= args.length) {
8671 name = null;
8672 newArgs = EMPTY_STRING_ARRAY;
8673 } else {
8674 name = args[opti];
8675 opti++;
8676 newArgs = new String[args.length - opti];
8677 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8678 args.length - opti);
8679 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008680 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008681 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008682 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008683 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8684 synchronized (this) {
8685 dumpOomLocked(fd, pw, args, opti, true);
8686 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008687 } else if ("provider".equals(cmd)) {
8688 String[] newArgs;
8689 String name;
8690 if (opti >= args.length) {
8691 name = null;
8692 newArgs = EMPTY_STRING_ARRAY;
8693 } else {
8694 name = args[opti];
8695 opti++;
8696 newArgs = new String[args.length - opti];
8697 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8698 }
8699 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8700 pw.println("No providers match: " + name);
8701 pw.println("Use -h for help.");
8702 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008703 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8704 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008705 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008706 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008707 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008708 String[] newArgs;
8709 String name;
8710 if (opti >= args.length) {
8711 name = null;
8712 newArgs = EMPTY_STRING_ARRAY;
8713 } else {
8714 name = args[opti];
8715 opti++;
8716 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008717 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8718 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008719 }
8720 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8721 pw.println("No services match: " + name);
8722 pw.println("Use -h for help.");
8723 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008724 } else if ("package".equals(cmd)) {
8725 String[] newArgs;
8726 if (opti >= args.length) {
8727 pw.println("package: no package name specified");
8728 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008729 } else {
8730 dumpPackage = args[opti];
8731 opti++;
8732 newArgs = new String[args.length - opti];
8733 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8734 args.length - opti);
8735 args = newArgs;
8736 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008737 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008738 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008739 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8740 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008741 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008742 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008743 } else {
8744 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008745 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8746 pw.println("Bad activity command, or no activities match: " + cmd);
8747 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008748 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008749 }
8750 if (!more) {
8751 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008752 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008753 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008754 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008755
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008756 // No piece of data specified, dump everything.
8757 synchronized (this) {
8758 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008759 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008760 if (needSep) {
8761 pw.println(" ");
8762 }
8763 if (dumpAll) {
8764 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008765 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008766 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008767 if (needSep) {
8768 pw.println(" ");
8769 }
8770 if (dumpAll) {
8771 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008772 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008773 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008774 if (needSep) {
8775 pw.println(" ");
8776 }
8777 if (dumpAll) {
8778 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008779 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008780 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008781 if (needSep) {
8782 pw.println(" ");
8783 }
8784 if (dumpAll) {
8785 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008786 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008787 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008788 if (needSep) {
8789 pw.println(" ");
8790 }
8791 if (dumpAll) {
8792 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008793 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008794 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008795 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008796 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008797 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008798
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008799 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008800 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008801 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8802 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008803 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8804 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008805 pw.println(" ");
8806 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008807 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8808 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008809 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008810 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008811 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008812 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008813 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008814 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008815 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008816 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008817 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008818 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008819 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008820 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008821 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8822 pw.println(" ");
8823 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008824 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008825 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008826 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008827 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008828 pw.println(" ");
8829 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008830 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008831 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008833
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008834 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008835 if (mMainStack.mPausingActivity != null) {
8836 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008837 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008838 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008839 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008840 if (dumpAll) {
8841 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8842 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008843 pw.println(" mDismissKeyguardOnNextActivity: "
8844 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008846
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008847 if (mRecentTasks.size() > 0) {
8848 pw.println();
8849 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008850
8851 final int N = mRecentTasks.size();
8852 for (int i=0; i<N; i++) {
8853 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008854 if (dumpPackage != null) {
8855 if (tr.realActivity == null ||
8856 !dumpPackage.equals(tr.realActivity)) {
8857 continue;
8858 }
8859 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008860 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8861 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008862 if (dumpAll) {
8863 mRecentTasks.get(i).dump(pw, " ");
8864 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008865 }
8866 }
8867
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008868 if (dumpAll) {
8869 pw.println(" ");
8870 pw.println(" mCurTask: " + mCurTask);
8871 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008872
8873 return true;
8874 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008875
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008876 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008877 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008878 boolean needSep = false;
8879 int numPers = 0;
8880
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008881 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8882
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008883 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008884 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8885 final int NA = procs.size();
8886 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008887 ProcessRecord r = procs.valueAt(ia);
8888 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8889 continue;
8890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008891 if (!needSep) {
8892 pw.println(" All known processes:");
8893 needSep = true;
8894 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008895 pw.print(r.persistent ? " *PERS*" : " *APP*");
8896 pw.print(" UID "); pw.print(procs.keyAt(ia));
8897 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008898 r.dump(pw, " ");
8899 if (r.persistent) {
8900 numPers++;
8901 }
8902 }
8903 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008904 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008905
8906 if (mIsolatedProcesses.size() > 0) {
8907 if (needSep) pw.println(" ");
8908 needSep = true;
8909 pw.println(" Isolated process list (sorted by uid):");
8910 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8911 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8912 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8913 continue;
8914 }
8915 pw.println(String.format("%sIsolated #%2d: %s",
8916 " ", i, r.toString()));
8917 }
8918 }
8919
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008920 if (mLruProcesses.size() > 0) {
8921 if (needSep) pw.println(" ");
8922 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008923 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008924 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008925 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008926 needSep = true;
8927 }
8928
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008929 if (dumpAll) {
8930 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008931 boolean printed = false;
8932 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8933 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8934 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8935 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008936 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008937 if (!printed) {
8938 if (needSep) pw.println(" ");
8939 needSep = true;
8940 pw.println(" PID mappings:");
8941 printed = true;
8942 }
8943 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8944 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 }
8946 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008947 }
8948
8949 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008950 synchronized (mPidsSelfLocked) {
8951 boolean printed = false;
8952 for (int i=0; i<mForegroundProcesses.size(); i++) {
8953 ProcessRecord r = mPidsSelfLocked.get(
8954 mForegroundProcesses.valueAt(i).pid);
8955 if (dumpPackage != null && (r == null
8956 || !dumpPackage.equals(r.info.packageName))) {
8957 continue;
8958 }
8959 if (!printed) {
8960 if (needSep) pw.println(" ");
8961 needSep = true;
8962 pw.println(" Foreground Processes:");
8963 printed = true;
8964 }
8965 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8966 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008968 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008969 }
8970
8971 if (mPersistentStartingProcesses.size() > 0) {
8972 if (needSep) pw.println(" ");
8973 needSep = true;
8974 pw.println(" Persisent processes that are starting:");
8975 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008976 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008978
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008979 if (mRemovedProcesses.size() > 0) {
8980 if (needSep) pw.println(" ");
8981 needSep = true;
8982 pw.println(" Processes that are being removed:");
8983 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008984 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008985 }
8986
8987 if (mProcessesOnHold.size() > 0) {
8988 if (needSep) pw.println(" ");
8989 needSep = true;
8990 pw.println(" Processes that are on old until the system is ready:");
8991 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008992 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008994
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008995 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008996
8997 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008998 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008999 long now = SystemClock.uptimeMillis();
9000 for (Map.Entry<String, SparseArray<Long>> procs
9001 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009002 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009003 SparseArray<Long> uids = procs.getValue();
9004 final int N = uids.size();
9005 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009006 int puid = uids.keyAt(i);
9007 ProcessRecord r = mProcessNames.get(pname, puid);
9008 if (dumpPackage != null && (r == null
9009 || !dumpPackage.equals(r.info.packageName))) {
9010 continue;
9011 }
9012 if (!printed) {
9013 if (needSep) pw.println(" ");
9014 needSep = true;
9015 pw.println(" Time since processes crashed:");
9016 printed = true;
9017 }
9018 pw.print(" Process "); pw.print(pname);
9019 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009020 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009021 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9022 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009023 }
9024 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009026
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009027 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009028 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009029 for (Map.Entry<String, SparseArray<Long>> procs
9030 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009031 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009032 SparseArray<Long> uids = procs.getValue();
9033 final int N = uids.size();
9034 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009035 int puid = uids.keyAt(i);
9036 ProcessRecord r = mProcessNames.get(pname, puid);
9037 if (dumpPackage != null && (r == null
9038 || !dumpPackage.equals(r.info.packageName))) {
9039 continue;
9040 }
9041 if (!printed) {
9042 if (needSep) pw.println(" ");
9043 needSep = true;
9044 pw.println(" Bad processes:");
9045 }
9046 pw.print(" Bad process "); pw.print(pname);
9047 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009048 pw.print(": crashed at time ");
9049 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009050 }
9051 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009053
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009054 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009055 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009056 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009057 if (dumpAll) {
9058 StringBuilder sb = new StringBuilder(128);
9059 sb.append(" mPreviousProcessVisibleTime: ");
9060 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9061 pw.println(sb);
9062 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009063 if (mHeavyWeightProcess != null) {
9064 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9065 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009066 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009067 if (dumpAll) {
9068 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009069 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009070 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009071 for (Map.Entry<String, Integer> entry
9072 : mCompatModePackages.getPackages().entrySet()) {
9073 String pkg = entry.getKey();
9074 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009075 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9076 continue;
9077 }
9078 if (!printed) {
9079 pw.println(" mScreenCompatPackages:");
9080 printed = true;
9081 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009082 pw.print(" "); pw.print(pkg); pw.print(": ");
9083 pw.print(mode); pw.println();
9084 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009085 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009086 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009087 if (mSleeping || mWentToSleep || mLockScreenShown) {
9088 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9089 + " mLockScreenShown " + mLockScreenShown);
9090 }
9091 if (mShuttingDown) {
9092 pw.println(" mShuttingDown=" + mShuttingDown);
9093 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009094 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9095 || mOrigWaitForDebugger) {
9096 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9097 + " mDebugTransient=" + mDebugTransient
9098 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9099 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009100 if (mOpenGlTraceApp != null) {
9101 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9102 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009103 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9104 || mProfileFd != null) {
9105 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9106 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9107 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9108 + mAutoStopProfiler);
9109 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009110 if (mAlwaysFinishActivities || mController != null) {
9111 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9112 + " mController=" + mController);
9113 }
9114 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009115 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009116 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009117 + " mProcessesReady=" + mProcessesReady
9118 + " mSystemReady=" + mSystemReady);
9119 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009120 + " mBooted=" + mBooted
9121 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009122 pw.print(" mLastPowerCheckRealtime=");
9123 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9124 pw.println("");
9125 pw.print(" mLastPowerCheckUptime=");
9126 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9127 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009128 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9129 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009130 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009131 pw.println(" mNumServiceProcs=" + mNumServiceProcs
9132 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009133 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009134
9135 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009136 }
9137
Dianne Hackborn287952c2010-09-22 22:34:31 -07009138 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009139 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009140 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009141 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009142 long now = SystemClock.uptimeMillis();
9143 for (int i=0; i<mProcessesToGc.size(); i++) {
9144 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009145 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9146 continue;
9147 }
9148 if (!printed) {
9149 if (needSep) pw.println(" ");
9150 needSep = true;
9151 pw.println(" Processes that are waiting to GC:");
9152 printed = true;
9153 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009154 pw.print(" Process "); pw.println(proc);
9155 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9156 pw.print(", last gced=");
9157 pw.print(now-proc.lastRequestedGc);
9158 pw.print(" ms ago, last lowMem=");
9159 pw.print(now-proc.lastLowMemory);
9160 pw.println(" ms ago");
9161
9162 }
9163 }
9164 return needSep;
9165 }
9166
9167 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9168 int opti, boolean dumpAll) {
9169 boolean needSep = false;
9170
9171 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009172 if (needSep) pw.println(" ");
9173 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009174 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009175 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009176 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009177 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9178 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9179 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9180 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9181 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009182 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009183 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009184 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009185 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009186 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009187 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009188
9189 if (needSep) pw.println(" ");
9190 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009191 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009192 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009193 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009194 needSep = true;
9195 }
9196
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009197 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009198
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009199 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009200 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009201 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009202 if (mHeavyWeightProcess != null) {
9203 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9204 }
9205
9206 return true;
9207 }
9208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009209 /**
9210 * There are three ways to call this:
9211 * - no service specified: dump all the services
9212 * - a flattened component name that matched an existing service was specified as the
9213 * first arg: dump that one service
9214 * - the first arg isn't the flattened component name of an existing service:
9215 * dump all services whose component contains the first arg as a substring
9216 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009217 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9218 int opti, boolean dumpAll) {
9219 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009220
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009221 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009222 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009223 try {
9224 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9225 for (UserInfo user : users) {
9226 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9227 services.add(r1);
9228 }
9229 }
9230 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009231 }
9232 }
9233 } else {
9234 ComponentName componentName = name != null
9235 ? ComponentName.unflattenFromString(name) : null;
9236 int objectId = 0;
9237 if (componentName == null) {
9238 // Not a '/' separated full component name; maybe an object ID?
9239 try {
9240 objectId = Integer.parseInt(name, 16);
9241 name = null;
9242 componentName = null;
9243 } catch (RuntimeException e) {
9244 }
9245 }
9246
9247 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009248 try {
9249 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9250 for (UserInfo user : users) {
9251 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9252 if (componentName != null) {
9253 if (r1.name.equals(componentName)) {
9254 services.add(r1);
9255 }
9256 } else if (name != null) {
9257 if (r1.name.flattenToString().contains(name)) {
9258 services.add(r1);
9259 }
9260 } else if (System.identityHashCode(r1) == objectId) {
9261 services.add(r1);
9262 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009263 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009264 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009265 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009266 }
9267 }
9268 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009269
9270 if (services.size() <= 0) {
9271 return false;
9272 }
9273
9274 boolean needSep = false;
9275 for (int i=0; i<services.size(); i++) {
9276 if (needSep) {
9277 pw.println();
9278 }
9279 needSep = true;
9280 dumpService("", fd, pw, services.get(i), args, dumpAll);
9281 }
9282 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009283 }
9284
9285 /**
9286 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9287 * there is a thread associated with the service.
9288 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009289 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9290 final ServiceRecord r, String[] args, boolean dumpAll) {
9291 String innerPrefix = prefix + " ";
9292 synchronized (this) {
9293 pw.print(prefix); pw.print("SERVICE ");
9294 pw.print(r.shortName); pw.print(" ");
9295 pw.print(Integer.toHexString(System.identityHashCode(r)));
9296 pw.print(" pid=");
9297 if (r.app != null) pw.println(r.app.pid);
9298 else pw.println("(not running)");
9299 if (dumpAll) {
9300 r.dump(pw, innerPrefix);
9301 }
9302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009304 pw.print(prefix); pw.println(" Client:");
9305 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009306 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009307 TransferPipe tp = new TransferPipe();
9308 try {
9309 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9310 tp.setBufferPrefix(prefix + " ");
9311 tp.go(fd);
9312 } finally {
9313 tp.kill();
9314 }
9315 } catch (IOException e) {
9316 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009317 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009318 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009319 }
9320 }
9321 }
9322
Marco Nelissen18cb2872011-11-15 11:19:53 -08009323 /**
9324 * There are three ways to call this:
9325 * - no provider specified: dump all the providers
9326 * - a flattened component name that matched an existing provider was specified as the
9327 * first arg: dump that one provider
9328 * - the first arg isn't the flattened component name of an existing provider:
9329 * dump all providers whose component contains the first arg as a substring
9330 */
9331 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9332 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009333 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009334 }
9335
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009336 static class ItemMatcher {
9337 ArrayList<ComponentName> components;
9338 ArrayList<String> strings;
9339 ArrayList<Integer> objects;
9340 boolean all;
9341
9342 ItemMatcher() {
9343 all = true;
9344 }
9345
9346 void build(String name) {
9347 ComponentName componentName = ComponentName.unflattenFromString(name);
9348 if (componentName != null) {
9349 if (components == null) {
9350 components = new ArrayList<ComponentName>();
9351 }
9352 components.add(componentName);
9353 all = false;
9354 } else {
9355 int objectId = 0;
9356 // Not a '/' separated full component name; maybe an object ID?
9357 try {
9358 objectId = Integer.parseInt(name, 16);
9359 if (objects == null) {
9360 objects = new ArrayList<Integer>();
9361 }
9362 objects.add(objectId);
9363 all = false;
9364 } catch (RuntimeException e) {
9365 // Not an integer; just do string match.
9366 if (strings == null) {
9367 strings = new ArrayList<String>();
9368 }
9369 strings.add(name);
9370 all = false;
9371 }
9372 }
9373 }
9374
9375 int build(String[] args, int opti) {
9376 for (; opti<args.length; opti++) {
9377 String name = args[opti];
9378 if ("--".equals(name)) {
9379 return opti+1;
9380 }
9381 build(name);
9382 }
9383 return opti;
9384 }
9385
9386 boolean match(Object object, ComponentName comp) {
9387 if (all) {
9388 return true;
9389 }
9390 if (components != null) {
9391 for (int i=0; i<components.size(); i++) {
9392 if (components.get(i).equals(comp)) {
9393 return true;
9394 }
9395 }
9396 }
9397 if (objects != null) {
9398 for (int i=0; i<objects.size(); i++) {
9399 if (System.identityHashCode(object) == objects.get(i)) {
9400 return true;
9401 }
9402 }
9403 }
9404 if (strings != null) {
9405 String flat = comp.flattenToString();
9406 for (int i=0; i<strings.size(); i++) {
9407 if (flat.contains(strings.get(i))) {
9408 return true;
9409 }
9410 }
9411 }
9412 return false;
9413 }
9414 }
9415
Dianne Hackborn625ac272010-09-17 18:29:22 -07009416 /**
9417 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009418 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009419 * - the cmd arg isn't the flattened component name of an existing activity:
9420 * dump all activity whose component contains the cmd as a substring
9421 * - A hex number of the ActivityRecord object instance.
9422 */
9423 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9424 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009425 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009426
9427 if ("all".equals(name)) {
9428 synchronized (this) {
9429 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009430 activities.add(r1);
9431 }
9432 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009433 } else if ("top".equals(name)) {
9434 synchronized (this) {
9435 final int N = mMainStack.mHistory.size();
9436 if (N > 0) {
9437 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9438 }
9439 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009440 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009441 ItemMatcher matcher = new ItemMatcher();
9442 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009443
9444 synchronized (this) {
9445 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009446 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009447 activities.add(r1);
9448 }
9449 }
9450 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009451 }
9452
9453 if (activities.size() <= 0) {
9454 return false;
9455 }
9456
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009457 String[] newArgs = new String[args.length - opti];
9458 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9459
Dianne Hackborn30d71892010-12-11 10:37:55 -08009460 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009461 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009462 for (int i=activities.size()-1; i>=0; i--) {
9463 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009464 if (needSep) {
9465 pw.println();
9466 }
9467 needSep = true;
9468 synchronized (this) {
9469 if (lastTask != r.task) {
9470 lastTask = r.task;
9471 pw.print("TASK "); pw.print(lastTask.affinity);
9472 pw.print(" id="); pw.println(lastTask.taskId);
9473 if (dumpAll) {
9474 lastTask.dump(pw, " ");
9475 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009476 }
9477 }
9478 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009479 }
9480 return true;
9481 }
9482
9483 /**
9484 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9485 * there is a thread associated with the activity.
9486 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009487 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009488 final ActivityRecord r, String[] args, boolean dumpAll) {
9489 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009490 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009491 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9492 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9493 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009494 if (r.app != null) pw.println(r.app.pid);
9495 else pw.println("(not running)");
9496 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009497 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009498 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009499 }
9500 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009501 // flush anything that is already in the PrintWriter since the thread is going
9502 // to write to the file descriptor directly
9503 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009504 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009505 TransferPipe tp = new TransferPipe();
9506 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009507 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9508 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009509 tp.go(fd);
9510 } finally {
9511 tp.kill();
9512 }
9513 } catch (IOException e) {
9514 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009515 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009516 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009517 }
9518 }
9519 }
9520
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009521 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009522 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009523 boolean needSep = false;
9524
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009525 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009526 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009527 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009528 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009529 Iterator it = mRegisteredReceivers.values().iterator();
9530 while (it.hasNext()) {
9531 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009532 if (dumpPackage != null && (r.app == null ||
9533 !dumpPackage.equals(r.app.info.packageName))) {
9534 continue;
9535 }
9536 if (!printed) {
9537 pw.println(" Registered Receivers:");
9538 needSep = true;
9539 printed = true;
9540 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009541 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009542 r.dump(pw, " ");
9543 }
9544 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009545
9546 if (mReceiverResolver.dump(pw, needSep ?
9547 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9548 " ", dumpPackage, false)) {
9549 needSep = true;
9550 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009551 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009552
9553 for (BroadcastQueue q : mBroadcastQueues) {
9554 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009556
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009557 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009558
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009559 if (mStickyBroadcasts != null && dumpPackage == null) {
9560 if (needSep) {
9561 pw.println();
9562 }
9563 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009564 pw.println(" Sticky broadcasts:");
9565 StringBuilder sb = new StringBuilder(128);
9566 for (Map.Entry<String, ArrayList<Intent>> ent
9567 : mStickyBroadcasts.entrySet()) {
9568 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009569 if (dumpAll) {
9570 pw.println(":");
9571 ArrayList<Intent> intents = ent.getValue();
9572 final int N = intents.size();
9573 for (int i=0; i<N; i++) {
9574 sb.setLength(0);
9575 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009576 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009577 pw.println(sb.toString());
9578 Bundle bundle = intents.get(i).getExtras();
9579 if (bundle != null) {
9580 pw.print(" ");
9581 pw.println(bundle.toString());
9582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009583 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009584 } else {
9585 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009586 }
9587 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009588 needSep = true;
9589 }
9590
9591 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009592 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009593 for (BroadcastQueue queue : mBroadcastQueues) {
9594 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9595 + queue.mBroadcastsScheduled);
9596 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009597 pw.println(" mHandler:");
9598 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009599 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009600 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009601
9602 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009603 }
9604
Marco Nelissen18cb2872011-11-15 11:19:53 -08009605 /**
9606 * Prints a list of ServiceRecords (dumpsys activity services)
9607 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009608 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009609 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009610 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009611
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009612 ItemMatcher matcher = new ItemMatcher();
9613 matcher.build(args, opti);
9614
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009615 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009616 try {
9617 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9618 for (UserInfo user : users) {
9619 if (mServiceMap.getAllServices(user.id).size() > 0) {
9620 boolean printed = false;
9621 long nowReal = SystemClock.elapsedRealtime();
9622 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9623 user.id).iterator();
9624 needSep = false;
9625 while (it.hasNext()) {
9626 ServiceRecord r = it.next();
9627 if (!matcher.match(r, r.name)) {
9628 continue;
9629 }
9630 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9631 continue;
9632 }
9633 if (!printed) {
9634 pw.println(" Active services:");
9635 printed = true;
9636 }
9637 if (needSep) {
9638 pw.println();
9639 }
9640 pw.print(" * ");
9641 pw.println(r);
9642 if (dumpAll) {
9643 r.dump(pw, " ");
9644 needSep = true;
9645 } else {
9646 pw.print(" app=");
9647 pw.println(r.app);
9648 pw.print(" created=");
9649 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9650 pw.print(" started=");
9651 pw.print(r.startRequested);
9652 pw.print(" connections=");
9653 pw.println(r.connections.size());
9654 if (r.connections.size() > 0) {
9655 pw.println(" Connections:");
9656 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9657 for (int i = 0; i < clist.size(); i++) {
9658 ConnectionRecord conn = clist.get(i);
9659 pw.print(" ");
9660 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009661 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009662 pw.print(" -> ");
9663 ProcessRecord proc = conn.binding.client;
9664 pw.println(proc != null ? proc.toShortString() : "null");
9665 }
9666 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009667 }
9668 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009669 if (dumpClient && r.app != null && r.app.thread != null) {
9670 pw.println(" Client:");
9671 pw.flush();
9672 try {
9673 TransferPipe tp = new TransferPipe();
9674 try {
9675 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9676 r, args);
9677 tp.setBufferPrefix(" ");
9678 // Short timeout, since blocking here can
9679 // deadlock with the application.
9680 tp.go(fd, 2000);
9681 } finally {
9682 tp.kill();
9683 }
9684 } catch (IOException e) {
9685 pw.println(" Failure while dumping the service: " + e);
9686 } catch (RemoteException e) {
9687 pw.println(" Got a RemoteException while dumping the service");
9688 }
9689 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009690 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009691 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009692 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009694 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009695 } catch (RemoteException re) {
9696
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009698
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009699 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009700 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009701 for (int i=0; i<mPendingServices.size(); i++) {
9702 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009703 if (!matcher.match(r, r.name)) {
9704 continue;
9705 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009706 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9707 continue;
9708 }
9709 if (!printed) {
9710 if (needSep) pw.println(" ");
9711 needSep = true;
9712 pw.println(" Pending services:");
9713 printed = true;
9714 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009715 pw.print(" * Pending "); pw.println(r);
9716 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009717 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009718 needSep = true;
9719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009720
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009721 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009722 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009723 for (int i=0; i<mRestartingServices.size(); i++) {
9724 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009725 if (!matcher.match(r, r.name)) {
9726 continue;
9727 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009728 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9729 continue;
9730 }
9731 if (!printed) {
9732 if (needSep) pw.println(" ");
9733 needSep = true;
9734 pw.println(" Restarting services:");
9735 printed = true;
9736 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009737 pw.print(" * Restarting "); pw.println(r);
9738 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009739 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009740 needSep = true;
9741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009742
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009743 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009744 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009745 for (int i=0; i<mStoppingServices.size(); i++) {
9746 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009747 if (!matcher.match(r, r.name)) {
9748 continue;
9749 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009750 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9751 continue;
9752 }
9753 if (!printed) {
9754 if (needSep) pw.println(" ");
9755 needSep = true;
9756 pw.println(" Stopping services:");
9757 printed = true;
9758 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009759 pw.print(" * Stopping "); pw.println(r);
9760 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009761 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009762 needSep = true;
9763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009764
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009765 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009766 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009767 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009768 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009769 = mServiceConnections.values().iterator();
9770 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009771 ArrayList<ConnectionRecord> r = it.next();
9772 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009773 ConnectionRecord cr = r.get(i);
9774 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9775 continue;
9776 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009777 if (dumpPackage != null && (cr.binding.client == null
9778 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9779 continue;
9780 }
9781 if (!printed) {
9782 if (needSep) pw.println(" ");
9783 needSep = true;
9784 pw.println(" Connection bindings to services:");
9785 printed = true;
9786 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009787 pw.print(" * "); pw.println(cr);
9788 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009790 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009791 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009792 }
9793 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009794
9795 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009796 }
9797
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009798 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009799 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009800 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009801
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009802 ItemMatcher matcher = new ItemMatcher();
9803 matcher.build(args, opti);
9804
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009805 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009806
9807 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009808
9809 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009810 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009811 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009812 ContentProviderRecord r = mLaunchingProviders.get(i);
9813 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9814 continue;
9815 }
9816 if (!printed) {
9817 if (needSep) pw.println(" ");
9818 needSep = true;
9819 pw.println(" Launching content providers:");
9820 printed = true;
9821 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009822 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009823 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009824 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009825 }
9826
9827 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009828 if (needSep) pw.println();
9829 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009830 pw.println("Granted Uri Permissions:");
9831 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9832 int uid = mGrantedUriPermissions.keyAt(i);
9833 HashMap<Uri, UriPermission> perms
9834 = mGrantedUriPermissions.valueAt(i);
9835 pw.print(" * UID "); pw.print(uid);
9836 pw.println(" holds:");
9837 for (UriPermission perm : perms.values()) {
9838 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009839 if (dumpAll) {
9840 perm.dump(pw, " ");
9841 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009842 }
9843 }
9844 needSep = true;
9845 }
9846
9847 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009848 }
9849
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009850 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009851 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009852 boolean needSep = false;
9853
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009854 if (mIntentSenderRecords.size() > 0) {
9855 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009856 Iterator<WeakReference<PendingIntentRecord>> it
9857 = mIntentSenderRecords.values().iterator();
9858 while (it.hasNext()) {
9859 WeakReference<PendingIntentRecord> ref = it.next();
9860 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009861 if (dumpPackage != null && (rec == null
9862 || !dumpPackage.equals(rec.key.packageName))) {
9863 continue;
9864 }
9865 if (!printed) {
9866 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9867 printed = true;
9868 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009869 needSep = true;
9870 if (rec != null) {
9871 pw.print(" * "); pw.println(rec);
9872 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009873 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009874 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009875 } else {
9876 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009877 }
9878 }
9879 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009880
9881 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009882 }
9883
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009884 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009885 String prefix, String label, boolean complete, boolean brief, boolean client,
9886 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009887 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009888 boolean needNL = false;
9889 final String innerPrefix = prefix + " ";
9890 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009891 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009892 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009893 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9894 continue;
9895 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009896 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009897 if (needNL) {
9898 pw.println(" ");
9899 needNL = false;
9900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009901 if (lastTask != r.task) {
9902 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009903 pw.print(prefix);
9904 pw.print(full ? "* " : " ");
9905 pw.println(lastTask);
9906 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009907 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009908 } else if (complete) {
9909 // Complete + brief == give a summary. Isn't that obvious?!?
9910 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009911 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009912 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009913 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009915 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009916 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9917 pw.print(" #"); pw.print(i); pw.print(": ");
9918 pw.println(r);
9919 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009920 r.dump(pw, innerPrefix);
9921 } else if (complete) {
9922 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009923 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009924 if (r.app != null) {
9925 pw.print(innerPrefix); pw.println(r.app);
9926 }
9927 }
9928 if (client && r.app != null && r.app.thread != null) {
9929 // flush anything that is already in the PrintWriter since the thread is going
9930 // to write to the file descriptor directly
9931 pw.flush();
9932 try {
9933 TransferPipe tp = new TransferPipe();
9934 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009935 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9936 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009937 // Short timeout, since blocking here can
9938 // deadlock with the application.
9939 tp.go(fd, 2000);
9940 } finally {
9941 tp.kill();
9942 }
9943 } catch (IOException e) {
9944 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9945 } catch (RemoteException e) {
9946 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9947 }
9948 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009950 }
9951 }
9952
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009953 private static String buildOomTag(String prefix, String space, int val, int base) {
9954 if (val == base) {
9955 if (space == null) return prefix;
9956 return prefix + " ";
9957 }
9958 return prefix + "+" + Integer.toString(val-base);
9959 }
9960
9961 private static final int dumpProcessList(PrintWriter pw,
9962 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009963 String prefix, String normalLabel, String persistentLabel,
9964 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009965 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009966 final int N = list.size()-1;
9967 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009968 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009969 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9970 continue;
9971 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009972 pw.println(String.format("%s%s #%2d: %s",
9973 prefix, (r.persistent ? persistentLabel : normalLabel),
9974 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009975 if (r.persistent) {
9976 numPers++;
9977 }
9978 }
9979 return numPers;
9980 }
9981
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009982 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009983 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009984 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009985 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009986
Dianne Hackborn905577f2011-09-07 18:31:28 -07009987 ArrayList<Pair<ProcessRecord, Integer>> list
9988 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9989 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009990 ProcessRecord r = origList.get(i);
9991 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9992 continue;
9993 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009994 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9995 }
9996
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009997 if (list.size() <= 0) {
9998 return false;
9999 }
10000
Dianne Hackborn905577f2011-09-07 18:31:28 -070010001 Comparator<Pair<ProcessRecord, Integer>> comparator
10002 = new Comparator<Pair<ProcessRecord, Integer>>() {
10003 @Override
10004 public int compare(Pair<ProcessRecord, Integer> object1,
10005 Pair<ProcessRecord, Integer> object2) {
10006 if (object1.first.setAdj != object2.first.setAdj) {
10007 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
10008 }
10009 if (object1.second.intValue() != object2.second.intValue()) {
10010 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
10011 }
10012 return 0;
10013 }
10014 };
10015
10016 Collections.sort(list, comparator);
10017
Dianne Hackborn287952c2010-09-22 22:34:31 -070010018 final long curRealtime = SystemClock.elapsedRealtime();
10019 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
10020 final long curUptime = SystemClock.uptimeMillis();
10021 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
10022
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010023 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -070010024 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010025 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010026 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070010027 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010028 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
10029 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010030 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
10031 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010032 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
10033 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010034 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
10035 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010036 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010037 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010038 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
10039 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
10040 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
10041 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10042 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10043 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10044 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10045 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010046 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10047 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010048 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10049 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010050 } else {
10051 oomAdj = Integer.toString(r.setAdj);
10052 }
10053 String schedGroup;
10054 switch (r.setSchedGroup) {
10055 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10056 schedGroup = "B";
10057 break;
10058 case Process.THREAD_GROUP_DEFAULT:
10059 schedGroup = "F";
10060 break;
10061 default:
10062 schedGroup = Integer.toString(r.setSchedGroup);
10063 break;
10064 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010065 String foreground;
10066 if (r.foregroundActivities) {
10067 foreground = "A";
10068 } else if (r.foregroundServices) {
10069 foreground = "S";
10070 } else {
10071 foreground = " ";
10072 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010073 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010074 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010075 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10076 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010077 if (r.adjSource != null || r.adjTarget != null) {
10078 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010079 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010080 if (r.adjTarget instanceof ComponentName) {
10081 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10082 } else if (r.adjTarget != null) {
10083 pw.print(r.adjTarget.toString());
10084 } else {
10085 pw.print("{null}");
10086 }
10087 pw.print("<=");
10088 if (r.adjSource instanceof ProcessRecord) {
10089 pw.print("Proc{");
10090 pw.print(((ProcessRecord)r.adjSource).toShortString());
10091 pw.println("}");
10092 } else if (r.adjSource != null) {
10093 pw.println(r.adjSource.toString());
10094 } else {
10095 pw.println("{null}");
10096 }
10097 }
10098 if (inclDetails) {
10099 pw.print(prefix);
10100 pw.print(" ");
10101 pw.print("oom: max="); pw.print(r.maxAdj);
10102 pw.print(" hidden="); pw.print(r.hiddenAdj);
10103 pw.print(" curRaw="); pw.print(r.curRawAdj);
10104 pw.print(" setRaw="); pw.print(r.setRawAdj);
10105 pw.print(" cur="); pw.print(r.curAdj);
10106 pw.print(" set="); pw.println(r.setAdj);
10107 pw.print(prefix);
10108 pw.print(" ");
10109 pw.print("keeping="); pw.print(r.keeping);
10110 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010111 pw.print(" empty="); pw.print(r.empty);
10112 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010113
10114 if (!r.keeping) {
10115 if (r.lastWakeTime != 0) {
10116 long wtime;
10117 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10118 synchronized (stats) {
10119 wtime = stats.getProcessWakeTime(r.info.uid,
10120 r.pid, curRealtime);
10121 }
10122 long timeUsed = wtime - r.lastWakeTime;
10123 pw.print(prefix);
10124 pw.print(" ");
10125 pw.print("keep awake over ");
10126 TimeUtils.formatDuration(realtimeSince, pw);
10127 pw.print(" used ");
10128 TimeUtils.formatDuration(timeUsed, pw);
10129 pw.print(" (");
10130 pw.print((timeUsed*100)/realtimeSince);
10131 pw.println("%)");
10132 }
10133 if (r.lastCpuTime != 0) {
10134 long timeUsed = r.curCpuTime - r.lastCpuTime;
10135 pw.print(prefix);
10136 pw.print(" ");
10137 pw.print("run cpu over ");
10138 TimeUtils.formatDuration(uptimeSince, pw);
10139 pw.print(" used ");
10140 TimeUtils.formatDuration(timeUsed, pw);
10141 pw.print(" (");
10142 pw.print((timeUsed*100)/uptimeSince);
10143 pw.println("%)");
10144 }
10145 }
10146 }
10147 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010148 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010149 }
10150
Dianne Hackbornb437e092011-08-05 17:50:29 -070010151 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010152 ArrayList<ProcessRecord> procs;
10153 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010154 if (args != null && args.length > start
10155 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010156 procs = new ArrayList<ProcessRecord>();
10157 int pid = -1;
10158 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010159 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010160 } catch (NumberFormatException e) {
10161
10162 }
10163 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10164 ProcessRecord proc = mLruProcesses.get(i);
10165 if (proc.pid == pid) {
10166 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010167 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010168 procs.add(proc);
10169 }
10170 }
10171 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010172 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010173 return null;
10174 }
10175 } else {
10176 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10177 }
10178 }
10179 return procs;
10180 }
10181
10182 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10183 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010184 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010185 if (procs == null) {
10186 return;
10187 }
10188
10189 long uptime = SystemClock.uptimeMillis();
10190 long realtime = SystemClock.elapsedRealtime();
10191 pw.println("Applications Graphics Acceleration Info:");
10192 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10193
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010194 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10195 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010196 if (r.thread != null) {
10197 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10198 pw.flush();
10199 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010200 TransferPipe tp = new TransferPipe();
10201 try {
10202 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10203 tp.go(fd);
10204 } finally {
10205 tp.kill();
10206 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010207 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010208 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010209 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010210 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010211 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010212 pw.flush();
10213 }
10214 }
10215 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010216 }
10217
Jeff Brown6754ba22011-12-14 20:20:01 -080010218 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10219 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10220 if (procs == null) {
10221 return;
10222 }
10223
10224 pw.println("Applications Database Info:");
10225
10226 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10227 ProcessRecord r = procs.get(i);
10228 if (r.thread != null) {
10229 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10230 pw.flush();
10231 try {
10232 TransferPipe tp = new TransferPipe();
10233 try {
10234 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10235 tp.go(fd);
10236 } finally {
10237 tp.kill();
10238 }
10239 } catch (IOException e) {
10240 pw.println("Failure while dumping the app: " + r);
10241 pw.flush();
10242 } catch (RemoteException e) {
10243 pw.println("Got a RemoteException while dumping the app " + r);
10244 pw.flush();
10245 }
10246 }
10247 }
10248 }
10249
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010250 final static class MemItem {
10251 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010252 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010253 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010254 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010255 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010256
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010257 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010258 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010259 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010260 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010261 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010262 }
10263 }
10264
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010265 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010266 boolean sort) {
10267 if (sort) {
10268 Collections.sort(items, new Comparator<MemItem>() {
10269 @Override
10270 public int compare(MemItem lhs, MemItem rhs) {
10271 if (lhs.pss < rhs.pss) {
10272 return 1;
10273 } else if (lhs.pss > rhs.pss) {
10274 return -1;
10275 }
10276 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010277 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010278 });
10279 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010280
10281 for (int i=0; i<items.size(); i++) {
10282 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010283 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010284 if (mi.subitems != null) {
10285 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10286 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010287 }
10288 }
10289
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010290 // These are in KB.
10291 static final long[] DUMP_MEM_BUCKETS = new long[] {
10292 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10293 120*1024, 160*1024, 200*1024,
10294 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10295 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10296 };
10297
Dianne Hackborn672342c2011-11-29 11:29:02 -080010298 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10299 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010300 int start = label.lastIndexOf('.');
10301 if (start >= 0) start++;
10302 else start = 0;
10303 int end = label.length();
10304 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10305 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10306 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10307 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010308 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010309 out.append(label, start, end);
10310 return;
10311 }
10312 }
10313 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010314 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010315 out.append(label, start, end);
10316 }
10317
10318 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10319 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10320 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10321 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10322 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10323 };
10324 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10325 "System", "Persistent", "Foreground",
10326 "Visible", "Perceptible", "Heavy Weight",
10327 "Backup", "A Services", "Home", "Previous",
10328 "B Services", "Background"
10329 };
10330
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010331 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010332 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010333 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010334 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010335 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010336
10337 int opti = 0;
10338 while (opti < args.length) {
10339 String opt = args[opti];
10340 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10341 break;
10342 }
10343 opti++;
10344 if ("-a".equals(opt)) {
10345 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010346 } else if ("--oom".equals(opt)) {
10347 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010348 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010349 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010350 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010351 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010352 pw.println("If [process] is specified it can be the name or ");
10353 pw.println("pid of a specific process to dump.");
10354 return;
10355 } else {
10356 pw.println("Unknown argument: " + opt + "; use -h for help");
10357 }
10358 }
10359
10360 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010361 if (procs == null) {
10362 return;
10363 }
10364
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010365 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010366 long uptime = SystemClock.uptimeMillis();
10367 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010368
10369 if (procs.size() == 1 || isCheckinRequest) {
10370 dumpAll = true;
10371 }
10372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010373 if (isCheckinRequest) {
10374 // short checkin version
10375 pw.println(uptime + "," + realtime);
10376 pw.flush();
10377 } else {
10378 pw.println("Applications Memory Usage (kB):");
10379 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10380 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010381
Dianne Hackbornb437e092011-08-05 17:50:29 -070010382 String[] innerArgs = new String[args.length-opti];
10383 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10384
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010385 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10386 long nativePss=0, dalvikPss=0, otherPss=0;
10387 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10388
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010389 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10390 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10391 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010392
10393 long totalPss = 0;
10394
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010395 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10396 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010397 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010398 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010399 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10400 pw.flush();
10401 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010402 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010403 if (dumpAll) {
10404 try {
10405 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10406 } catch (RemoteException e) {
10407 if (!isCheckinRequest) {
10408 pw.println("Got RemoteException!");
10409 pw.flush();
10410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010411 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010412 } else {
10413 mi = new Debug.MemoryInfo();
10414 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010415 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010416
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010417 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010418 long myTotalPss = mi.getTotalPss();
10419 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010420 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010421 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010422 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010423
10424 nativePss += mi.nativePss;
10425 dalvikPss += mi.dalvikPss;
10426 otherPss += mi.otherPss;
10427 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10428 long mem = mi.getOtherPss(j);
10429 miscPss[j] += mem;
10430 otherPss -= mem;
10431 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010432
10433 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010434 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10435 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010436 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010437 if (oomProcs[oomIndex] == null) {
10438 oomProcs[oomIndex] = new ArrayList<MemItem>();
10439 }
10440 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010441 break;
10442 }
10443 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010445 }
10446 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010447
10448 if (!isCheckinRequest && procs.size() > 1) {
10449 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10450
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010451 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10452 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10453 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010454 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010455 String label = Debug.MemoryInfo.getOtherLabel(j);
10456 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010457 }
10458
Dianne Hackbornb437e092011-08-05 17:50:29 -070010459 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10460 for (int j=0; j<oomPss.length; j++) {
10461 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010462 String label = DUMP_MEM_OOM_LABEL[j];
10463 MemItem item = new MemItem(label, label, oomPss[j],
10464 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010465 item.subitems = oomProcs[j];
10466 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010467 }
10468 }
10469
Dianne Hackborn672342c2011-11-29 11:29:02 -080010470 if (outTag != null || outStack != null) {
10471 if (outTag != null) {
10472 appendMemBucket(outTag, totalPss, "total", false);
10473 }
10474 if (outStack != null) {
10475 appendMemBucket(outStack, totalPss, "total", true);
10476 }
10477 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010478 for (int i=0; i<oomMems.size(); i++) {
10479 MemItem miCat = oomMems.get(i);
10480 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10481 continue;
10482 }
10483 if (miCat.id < ProcessList.SERVICE_ADJ
10484 || miCat.id == ProcessList.HOME_APP_ADJ
10485 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010486 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10487 outTag.append(" / ");
10488 }
10489 if (outStack != null) {
10490 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10491 if (firstLine) {
10492 outStack.append(":");
10493 firstLine = false;
10494 }
10495 outStack.append("\n\t at ");
10496 } else {
10497 outStack.append("$");
10498 }
10499 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010500 for (int j=0; j<miCat.subitems.size(); j++) {
10501 MemItem mi = miCat.subitems.get(j);
10502 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010503 if (outTag != null) {
10504 outTag.append(" ");
10505 }
10506 if (outStack != null) {
10507 outStack.append("$");
10508 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010509 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010510 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10511 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10512 }
10513 if (outStack != null) {
10514 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10515 }
10516 }
10517 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10518 outStack.append("(");
10519 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10520 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10521 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10522 outStack.append(":");
10523 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10524 }
10525 }
10526 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010527 }
10528 }
10529 }
10530 }
10531
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010532 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010533 pw.println();
10534 pw.println("Total PSS by process:");
10535 dumpMemItems(pw, " ", procMems, true);
10536 pw.println();
10537 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010538 pw.println("Total PSS by OOM adjustment:");
10539 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010540 if (!oomOnly) {
10541 PrintWriter out = categoryPw != null ? categoryPw : pw;
10542 out.println();
10543 out.println("Total PSS by category:");
10544 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010545 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010546 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010547 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010548 final int[] SINGLE_LONG_FORMAT = new int[] {
10549 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10550 };
10551 long[] longOut = new long[1];
10552 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10553 SINGLE_LONG_FORMAT, null, longOut, null);
10554 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10555 longOut[0] = 0;
10556 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10557 SINGLE_LONG_FORMAT, null, longOut, null);
10558 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10559 longOut[0] = 0;
10560 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10561 SINGLE_LONG_FORMAT, null, longOut, null);
10562 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10563 longOut[0] = 0;
10564 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10565 SINGLE_LONG_FORMAT, null, longOut, null);
10566 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10567 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10568 pw.print(shared); pw.println(" kB");
10569 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10570 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010572 }
10573
10574 /**
10575 * Searches array of arguments for the specified string
10576 * @param args array of argument strings
10577 * @param value value to search for
10578 * @return true if the value is contained in the array
10579 */
10580 private static boolean scanArgs(String[] args, String value) {
10581 if (args != null) {
10582 for (String arg : args) {
10583 if (value.equals(arg)) {
10584 return true;
10585 }
10586 }
10587 }
10588 return false;
10589 }
10590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010591 private final void killServicesLocked(ProcessRecord app,
10592 boolean allowRestart) {
10593 // Report disconnected services.
10594 if (false) {
10595 // XXX we are letting the client link to the service for
10596 // death notifications.
10597 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010598 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010599 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010600 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010601 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010602 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010603 = r.connections.values().iterator();
10604 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010605 ArrayList<ConnectionRecord> cl = jt.next();
10606 for (int i=0; i<cl.size(); i++) {
10607 ConnectionRecord c = cl.get(i);
10608 if (c.binding.client != app) {
10609 try {
10610 //c.conn.connected(r.className, null);
10611 } catch (Exception e) {
10612 // todo: this should be asynchronous!
10613 Slog.w(TAG, "Exception thrown disconnected servce "
10614 + r.shortName
10615 + " from app " + app.processName, e);
10616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010617 }
10618 }
10619 }
10620 }
10621 }
10622 }
10623 }
10624
10625 // Clean up any connections this application has to other services.
10626 if (app.connections.size() > 0) {
10627 Iterator<ConnectionRecord> it = app.connections.iterator();
10628 while (it.hasNext()) {
10629 ConnectionRecord r = it.next();
10630 removeConnectionLocked(r, app, null);
10631 }
10632 }
10633 app.connections.clear();
10634
10635 if (app.services.size() != 0) {
10636 // Any services running in the application need to be placed
10637 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010638 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010640 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010641 synchronized (sr.stats.getBatteryStats()) {
10642 sr.stats.stopLaunchedLocked();
10643 }
10644 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010645 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010646 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010647 if (mStoppingServices.remove(sr)) {
10648 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10649 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010650
10651 boolean hasClients = sr.bindings.size() > 0;
10652 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010653 Iterator<IntentBindRecord> bindings
10654 = sr.bindings.values().iterator();
10655 while (bindings.hasNext()) {
10656 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010657 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010658 + ": shouldUnbind=" + b.hasBound);
10659 b.binder = null;
10660 b.requested = b.received = b.hasBound = false;
10661 }
10662 }
10663
Dianne Hackborn070783f2010-12-29 16:46:28 -080010664 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10665 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010666 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010667 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010668 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010669 sr.crashCount, sr.shortName, app.pid);
10670 bringDownServiceLocked(sr, true);
10671 } else if (!allowRestart) {
10672 bringDownServiceLocked(sr, true);
10673 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010674 boolean canceled = scheduleServiceRestartLocked(sr, true);
10675
10676 // Should the service remain running? Note that in the
10677 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010678 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010679 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10680 if (sr.pendingStarts.size() == 0) {
10681 sr.startRequested = false;
10682 if (!hasClients) {
10683 // Whoops, no reason to restart!
10684 bringDownServiceLocked(sr, true);
10685 }
10686 }
10687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010688 }
10689 }
10690
10691 if (!allowRestart) {
10692 app.services.clear();
10693 }
10694 }
10695
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010696 // Make sure we have no more records on the stopping list.
10697 int i = mStoppingServices.size();
10698 while (i > 0) {
10699 i--;
10700 ServiceRecord sr = mStoppingServices.get(i);
10701 if (sr.app == app) {
10702 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010703 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010704 }
10705 }
10706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010707 app.executingServices.clear();
10708 }
10709
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010710 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10711 ContentProviderRecord cpr, boolean always) {
10712 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10713
10714 if (!inLaunching || always) {
10715 synchronized (cpr) {
10716 cpr.launchingApp = null;
10717 cpr.notifyAll();
10718 }
10719 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
10720 String names[] = cpr.info.authority.split(";");
10721 for (int j = 0; j < names.length; j++) {
10722 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010723 }
10724 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010725
10726 for (int i=0; i<cpr.connections.size(); i++) {
10727 ContentProviderConnection conn = cpr.connections.get(i);
10728 if (conn.waiting) {
10729 // If this connection is waiting for the provider, then we don't
10730 // need to mess with its process unless we are always removing
10731 // or for some reason the provider is not currently launching.
10732 if (inLaunching && !always) {
10733 continue;
10734 }
10735 }
10736 ProcessRecord capp = conn.client;
10737 conn.dead = true;
10738 if (conn.stableCount > 0) {
10739 if (!capp.persistent && capp.thread != null
10740 && capp.pid != 0
10741 && capp.pid != MY_PID) {
10742 Slog.i(TAG, "Kill " + capp.processName
10743 + " (pid " + capp.pid + "): provider " + cpr.info.name
10744 + " in dying process " + (proc != null ? proc.processName : "??"));
10745 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10746 capp.processName, capp.setAdj, "dying provider "
10747 + cpr.name.toShortString());
10748 Process.killProcessQuiet(capp.pid);
10749 }
10750 } else if (capp.thread != null && conn.provider.provider != null) {
10751 try {
10752 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10753 } catch (RemoteException e) {
10754 }
10755 // In the protocol here, we don't expect the client to correctly
10756 // clean up this connection, we'll just remove it.
10757 cpr.connections.remove(i);
10758 conn.client.conProviders.remove(conn);
10759 }
10760 }
10761
10762 if (inLaunching && always) {
10763 mLaunchingProviders.remove(cpr);
10764 }
10765 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010766 }
10767
10768 /**
10769 * Main code for cleaning up a process when it has gone away. This is
10770 * called both as a result of the process dying, or directly when stopping
10771 * a process when running in single process mode.
10772 */
10773 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010774 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010775 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010776 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010777 }
10778
Dianne Hackborn36124872009-10-08 16:22:03 -070010779 mProcessesToGc.remove(app);
10780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010781 // Dismiss any open dialogs.
10782 if (app.crashDialog != null) {
10783 app.crashDialog.dismiss();
10784 app.crashDialog = null;
10785 }
10786 if (app.anrDialog != null) {
10787 app.anrDialog.dismiss();
10788 app.anrDialog = null;
10789 }
10790 if (app.waitDialog != null) {
10791 app.waitDialog.dismiss();
10792 app.waitDialog = null;
10793 }
10794
10795 app.crashing = false;
10796 app.notResponding = false;
10797
10798 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010799 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010800 app.thread = null;
10801 app.forcingToForeground = null;
10802 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010803 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010804 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010805 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010806
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010807 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010808
10809 boolean restart = false;
10810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010811 // Remove published content providers.
10812 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010813 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010814 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010815 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010816
10817 final boolean always = app.bad || !allowRestart;
10818 if (removeDyingProviderLocked(app, cpr, always) || always) {
10819 // We left the provider in the launching list, need to
10820 // restart it.
10821 restart = true;
10822 }
10823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010824 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010825 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010826 }
10827 app.pubProviders.clear();
10828 }
10829
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010830 // Take care of any launching providers waiting for this process.
10831 if (checkAppInLaunchingProvidersLocked(app, false)) {
10832 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010833 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010835 // Unregister from connected content providers.
10836 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010837 for (int i=0; i<app.conProviders.size(); i++) {
10838 ContentProviderConnection conn = app.conProviders.get(i);
10839 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010840 }
10841 app.conProviders.clear();
10842 }
10843
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010844 // At this point there may be remaining entries in mLaunchingProviders
10845 // where we were the only one waiting, so they are no longer of use.
10846 // Look for these and clean up if found.
10847 // XXX Commented out for now. Trying to figure out a way to reproduce
10848 // the actual situation to identify what is actually going on.
10849 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010850 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010851 ContentProviderRecord cpr = (ContentProviderRecord)
10852 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010853 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010854 synchronized (cpr) {
10855 cpr.launchingApp = null;
10856 cpr.notifyAll();
10857 }
10858 }
10859 }
10860 }
10861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010862 skipCurrentReceiverLocked(app);
10863
10864 // Unregister any receivers.
10865 if (app.receivers.size() > 0) {
10866 Iterator<ReceiverList> it = app.receivers.iterator();
10867 while (it.hasNext()) {
10868 removeReceiverLocked(it.next());
10869 }
10870 app.receivers.clear();
10871 }
10872
Christopher Tate181fafa2009-05-14 11:12:14 -070010873 // If the app is undergoing backup, tell the backup manager about it
10874 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010875 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010876 try {
10877 IBackupManager bm = IBackupManager.Stub.asInterface(
10878 ServiceManager.getService(Context.BACKUP_SERVICE));
10879 bm.agentDisconnected(app.info.packageName);
10880 } catch (RemoteException e) {
10881 // can't happen; backup manager is local
10882 }
10883 }
10884
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010885 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10886 ProcessChangeItem item = mPendingProcessChanges.get(i);
10887 if (item.pid == app.pid) {
10888 mPendingProcessChanges.remove(i);
10889 mAvailProcessChanges.add(item);
10890 }
10891 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010892 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010894 // If the caller is restarting this app, then leave it in its
10895 // current lists and let the caller take care of it.
10896 if (restarting) {
10897 return;
10898 }
10899
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010900 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010901 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010902 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010903 mProcessNames.remove(app.processName, app.uid);
10904 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010905 if (mHeavyWeightProcess == app) {
10906 mHeavyWeightProcess = null;
10907 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010909 } else if (!app.removed) {
10910 // This app is persistent, so we need to keep its record around.
10911 // If it is not already on the pending app list, add it there
10912 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010913 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10914 mPersistentStartingProcesses.add(app);
10915 restart = true;
10916 }
10917 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010918 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10919 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010920 mProcessesOnHold.remove(app);
10921
The Android Open Source Project4df24232009-03-05 14:34:35 -080010922 if (app == mHomeProcess) {
10923 mHomeProcess = null;
10924 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010925 if (app == mPreviousProcess) {
10926 mPreviousProcess = null;
10927 }
10928
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010929 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010930 // We have components that still need to be running in the
10931 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010932 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010933 startProcessLocked(app, "restart", app.processName);
10934 } else if (app.pid > 0 && app.pid != MY_PID) {
10935 // Goodbye!
10936 synchronized (mPidsSelfLocked) {
10937 mPidsSelfLocked.remove(app.pid);
10938 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10939 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010940 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010941 }
10942 }
10943
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010944 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10945 // Look through the content providers we are waiting to have launched,
10946 // and if any run in this process then either schedule a restart of
10947 // the process or kill the client waiting for it if this process has
10948 // gone bad.
10949 int NL = mLaunchingProviders.size();
10950 boolean restart = false;
10951 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010952 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010953 if (cpr.launchingApp == app) {
10954 if (!alwaysBad && !app.bad) {
10955 restart = true;
10956 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010957 removeDyingProviderLocked(app, cpr, true);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010958 NL = mLaunchingProviders.size();
10959 }
10960 }
10961 }
10962 return restart;
10963 }
10964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010965 // =========================================================
10966 // SERVICES
10967 // =========================================================
10968
10969 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10970 ActivityManager.RunningServiceInfo info =
10971 new ActivityManager.RunningServiceInfo();
10972 info.service = r.name;
10973 if (r.app != null) {
10974 info.pid = r.app.pid;
10975 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010976 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010977 info.process = r.processName;
10978 info.foreground = r.isForeground;
10979 info.activeSince = r.createTime;
10980 info.started = r.startRequested;
10981 info.clientCount = r.connections.size();
10982 info.crashCount = r.crashCount;
10983 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010984 if (r.isForeground) {
10985 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10986 }
10987 if (r.startRequested) {
10988 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10989 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010990 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010991 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10992 }
10993 if (r.app != null && r.app.persistent) {
10994 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10995 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010996
10997 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10998 for (int i=0; i<connl.size(); i++) {
10999 ConnectionRecord conn = connl.get(i);
11000 if (conn.clientLabel != 0) {
11001 info.clientPackage = conn.binding.client.info.packageName;
11002 info.clientLabel = conn.clientLabel;
11003 return info;
11004 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011005 }
11006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011007 return info;
11008 }
11009
11010 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
11011 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011012 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011013 synchronized (this) {
11014 ArrayList<ActivityManager.RunningServiceInfo> res
11015 = new ArrayList<ActivityManager.RunningServiceInfo>();
11016
Amith Yamasani742a6712011-05-04 14:49:28 -070011017 int userId = UserId.getUserId(Binder.getCallingUid());
11018 if (mServiceMap.getAllServices(userId).size() > 0) {
11019 Iterator<ServiceRecord> it
11020 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011021 while (it.hasNext() && res.size() < maxNum) {
11022 res.add(makeRunningServiceInfoLocked(it.next()));
11023 }
11024 }
11025
11026 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
11027 ServiceRecord r = mRestartingServices.get(i);
11028 ActivityManager.RunningServiceInfo info =
11029 makeRunningServiceInfoLocked(r);
11030 info.restarting = r.nextRestartTime;
11031 res.add(info);
11032 }
11033
11034 return res;
11035 }
11036 }
11037
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011038 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011039 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011040 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011041 int userId = UserId.getUserId(Binder.getCallingUid());
11042 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011043 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011044 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
11045 for (int i=0; i<conn.size(); i++) {
11046 if (conn.get(i).clientIntent != null) {
11047 return conn.get(i).clientIntent;
11048 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011049 }
11050 }
11051 }
11052 }
11053 return null;
11054 }
11055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011056 private final ServiceRecord findServiceLocked(ComponentName name,
11057 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011058 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011059 return r == token ? r : null;
11060 }
11061
11062 private final class ServiceLookupResult {
11063 final ServiceRecord record;
11064 final String permission;
11065
11066 ServiceLookupResult(ServiceRecord _record, String _permission) {
11067 record = _record;
11068 permission = _permission;
11069 }
11070 };
11071
11072 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011073 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011074 ServiceRecord r = null;
11075 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011076 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011077 }
11078 if (r == null) {
11079 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070011080 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011081 }
11082
11083 if (r == null) {
11084 try {
11085 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011086 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011087 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011088 ServiceInfo sInfo =
11089 rInfo != null ? rInfo.serviceInfo : null;
11090 if (sInfo == null) {
11091 return null;
11092 }
11093
11094 ComponentName name = new ComponentName(
11095 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070011096 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011097 } catch (RemoteException ex) {
11098 // pm is in same process, this will never happen.
11099 }
11100 }
11101 if (r != null) {
11102 int callingPid = Binder.getCallingPid();
11103 int callingUid = Binder.getCallingUid();
11104 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011105 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011106 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011107 if (!r.exported) {
11108 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11109 + " from pid=" + callingPid
11110 + ", uid=" + callingUid
11111 + " that is not exported from uid " + r.appInfo.uid);
11112 return new ServiceLookupResult(null, "not exported from uid "
11113 + r.appInfo.uid);
11114 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011115 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011116 + " from pid=" + callingPid
11117 + ", uid=" + callingUid
11118 + " requires " + r.permission);
11119 return new ServiceLookupResult(null, r.permission);
11120 }
11121 return new ServiceLookupResult(r, null);
11122 }
11123 return null;
11124 }
11125
11126 private class ServiceRestarter implements Runnable {
11127 private ServiceRecord mService;
11128
11129 void setService(ServiceRecord service) {
11130 mService = service;
11131 }
11132
11133 public void run() {
11134 synchronized(ActivityManagerService.this) {
11135 performServiceRestartLocked(mService);
11136 }
11137 }
11138 }
11139
11140 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011141 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011142 ServiceRecord r = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011143 if (DEBUG_SERVICE) Slog.v(TAG, "retrieveServiceLocked: " + service
11144 + " type=" + resolvedType + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070011145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011146 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011147 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011148 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011149 if (r == null) {
11150 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011151 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070011152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011153 if (r == null) {
11154 try {
11155 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011156 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011157 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011158 ServiceInfo sInfo =
11159 rInfo != null ? rInfo.serviceInfo : null;
11160 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011161 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011162 ": not found");
11163 return null;
11164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 ComponentName name = new ComponentName(
11166 sInfo.applicationInfo.packageName, sInfo.name);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011167 if (userId > 0) {
11168 if (isSingleton(sInfo.processName, sInfo.applicationInfo)
11169 || (sInfo.flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
11170 userId = 0;
11171 } else if ((sInfo.flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
11172 if (checkComponentPermission(
11173 android.Manifest.permission.INTERACT_ACROSS_USERS,
11174 callingPid, callingUid, -1, true)
11175 == PackageManager.PERMISSION_GRANTED) {
11176 userId = 0;
11177 } else {
11178 String msg = "Permission Denial: Service " + name
11179 + " requests FLAG_SINGLE_USER, but app does not hold "
11180 + android.Manifest.permission.INTERACT_ACROSS_USERS;
11181 Slog.w(TAG, msg);
11182 throw new SecurityException(msg);
11183 }
11184 }
11185 sInfo = new ServiceInfo(sInfo);
11186 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
11187 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011188 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011189 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011190 Intent.FilterComparison filter = new Intent.FilterComparison(
11191 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011192 ServiceRestarter res = new ServiceRestarter();
11193 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11194 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11195 synchronized (stats) {
11196 ss = stats.getServiceStatsLocked(
11197 sInfo.applicationInfo.uid, sInfo.packageName,
11198 sInfo.name);
11199 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080011200 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011201 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070011202 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
11203 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204
11205 // Make sure this component isn't in the pending list.
11206 int N = mPendingServices.size();
11207 for (int i=0; i<N; i++) {
11208 ServiceRecord pr = mPendingServices.get(i);
11209 if (pr.name.equals(name)) {
11210 mPendingServices.remove(i);
11211 i--;
11212 N--;
11213 }
11214 }
11215 }
11216 } catch (RemoteException ex) {
11217 // pm is in same process, this will never happen.
11218 }
11219 }
11220 if (r != null) {
11221 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011222 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011223 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011224 if (!r.exported) {
11225 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11226 + " from pid=" + callingPid
11227 + ", uid=" + callingUid
11228 + " that is not exported from uid " + r.appInfo.uid);
11229 return new ServiceLookupResult(null, "not exported from uid "
11230 + r.appInfo.uid);
11231 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011232 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011233 + " from pid=" + callingPid
11234 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011235 + " requires " + r.permission);
11236 return new ServiceLookupResult(null, r.permission);
11237 }
11238 return new ServiceLookupResult(r, null);
11239 }
11240 return null;
11241 }
11242
Dianne Hackborn287952c2010-09-22 22:34:31 -070011243 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
11244 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11245 + why + " of " + r + " in app " + r.app);
11246 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11247 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011248 long now = SystemClock.uptimeMillis();
11249 if (r.executeNesting == 0 && r.app != null) {
11250 if (r.app.executingServices.size() == 0) {
11251 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11252 msg.obj = r.app;
11253 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11254 }
11255 r.app.executingServices.add(r);
11256 }
11257 r.executeNesting++;
11258 r.executingStart = now;
11259 }
11260
11261 private final void sendServiceArgsLocked(ServiceRecord r,
11262 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011263 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011264 if (N == 0) {
11265 return;
11266 }
11267
Dianne Hackborn39792d22010-08-19 18:01:52 -070011268 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011269 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011270 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011271 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11272 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011273 if (si.intent == null && N > 1) {
11274 // If somehow we got a dummy null intent in the middle,
11275 // then skip it. DO NOT skip a null intent when it is
11276 // the only one in the list -- this is to support the
11277 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011278 continue;
11279 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011280 si.deliveredTime = SystemClock.uptimeMillis();
11281 r.deliveredStarts.add(si);
11282 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011283 if (si.neededGrants != null) {
11284 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
11285 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011286 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011287 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011288 if (!oomAdjusted) {
11289 oomAdjusted = true;
11290 updateOomAdjLocked(r.app);
11291 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011292 int flags = 0;
Dianne Hackbornd8f10242012-05-08 17:14:58 -070011293 if (si.deliveryCount > 1) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011294 flags |= Service.START_FLAG_RETRY;
11295 }
11296 if (si.doneExecutingCount > 0) {
11297 flags |= Service.START_FLAG_REDELIVERY;
11298 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011299 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011300 } catch (RemoteException e) {
11301 // Remote process gone... we'll let the normal cleanup take
11302 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011303 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011304 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011305 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011306 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011307 break;
11308 }
11309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011310 }
11311
11312 private final boolean requestServiceBindingLocked(ServiceRecord r,
11313 IntentBindRecord i, boolean rebind) {
11314 if (r.app == null || r.app.thread == null) {
11315 // If service is not currently running, can't yet bind.
11316 return false;
11317 }
11318 if ((!i.requested || rebind) && i.apps.size() > 0) {
11319 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011320 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011321 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11322 if (!rebind) {
11323 i.requested = true;
11324 }
11325 i.hasBound = true;
11326 i.doRebind = false;
11327 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011328 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011329 return false;
11330 }
11331 }
11332 return true;
11333 }
11334
11335 private final void requestServiceBindingsLocked(ServiceRecord r) {
11336 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11337 while (bindings.hasNext()) {
11338 IntentBindRecord i = bindings.next();
11339 if (!requestServiceBindingLocked(r, i, false)) {
11340 break;
11341 }
11342 }
11343 }
11344
11345 private final void realStartServiceLocked(ServiceRecord r,
11346 ProcessRecord app) throws RemoteException {
11347 if (app.thread == null) {
11348 throw new RemoteException();
11349 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011350 if (DEBUG_MU)
11351 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011352 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011353 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011354 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011355
11356 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011357 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011358 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011359
11360 boolean created = false;
11361 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011362 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011363 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011364 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011365 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011366 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011367 synchronized (r.stats.getBatteryStats()) {
11368 r.stats.startLaunchedLocked();
11369 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011370 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011371 app.thread.scheduleCreateService(r, r.serviceInfo,
11372 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011373 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011374 created = true;
11375 } finally {
11376 if (!created) {
11377 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011378 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379 }
11380 }
11381
11382 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011383
11384 // If the service is in the started state, and there are no
11385 // pending arguments, then fake up one so its onStartCommand() will
11386 // be called.
11387 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011388 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011389 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011390 }
11391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011392 sendServiceArgsLocked(r, true);
11393 }
11394
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011395 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11396 boolean allowCancel) {
11397 boolean canceled = false;
11398
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011399 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011400 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011401 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011402
Dianne Hackborn070783f2010-12-29 16:46:28 -080011403 if ((r.serviceInfo.applicationInfo.flags
11404 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11405 minDuration /= 4;
11406 }
11407
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011408 // Any delivered but not yet finished starts should be put back
11409 // on the pending list.
11410 final int N = r.deliveredStarts.size();
11411 if (N > 0) {
11412 for (int i=N-1; i>=0; i--) {
11413 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011414 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011415 if (si.intent == null) {
11416 // We'll generate this again if needed.
11417 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11418 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11419 r.pendingStarts.add(0, si);
11420 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11421 dur *= 2;
11422 if (minDuration < dur) minDuration = dur;
11423 if (resetTime < dur) resetTime = dur;
11424 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011425 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011426 + r.name);
11427 canceled = true;
11428 }
11429 }
11430 r.deliveredStarts.clear();
11431 }
11432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011433 r.totalRestartCount++;
11434 if (r.restartDelay == 0) {
11435 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011436 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011437 } else {
11438 // If it has been a "reasonably long time" since the service
11439 // was started, then reset our restart duration back to
11440 // the beginning, so we don't infinitely increase the duration
11441 // on a service that just occasionally gets killed (which is
11442 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011443 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011444 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011445 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011446 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011447 if ((r.serviceInfo.applicationInfo.flags
11448 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11449 // Services in peristent processes will restart much more
11450 // quickly, since they are pretty important. (Think SystemUI).
11451 r.restartDelay += minDuration/2;
11452 } else {
11453 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11454 if (r.restartDelay < minDuration) {
11455 r.restartDelay = minDuration;
11456 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011458 }
11459 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011460
11461 r.nextRestartTime = now + r.restartDelay;
11462
11463 // Make sure that we don't end up restarting a bunch of services
11464 // all at the same time.
11465 boolean repeat;
11466 do {
11467 repeat = false;
11468 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11469 ServiceRecord r2 = mRestartingServices.get(i);
11470 if (r2 != r && r.nextRestartTime
11471 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11472 && r.nextRestartTime
11473 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11474 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11475 r.restartDelay = r.nextRestartTime - now;
11476 repeat = true;
11477 break;
11478 }
11479 }
11480 } while (repeat);
11481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011482 if (!mRestartingServices.contains(r)) {
11483 mRestartingServices.add(r);
11484 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011485
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011486 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011488 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011489 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011490 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011491 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011492 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011493 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011494 r.shortName, r.restartDelay);
11495
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011496 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011497 }
11498
11499 final void performServiceRestartLocked(ServiceRecord r) {
11500 if (!mRestartingServices.contains(r)) {
11501 return;
11502 }
11503 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11504 }
11505
11506 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11507 if (r.restartDelay == 0) {
11508 return false;
11509 }
11510 r.resetRestartCounter();
11511 mRestartingServices.remove(r);
11512 mHandler.removeCallbacks(r.restarter);
11513 return true;
11514 }
11515
11516 private final boolean bringUpServiceLocked(ServiceRecord r,
11517 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011518 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011519 //r.dump(" ");
11520
Dianne Hackborn36124872009-10-08 16:22:03 -070011521 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011522 sendServiceArgsLocked(r, false);
11523 return true;
11524 }
11525
11526 if (!whileRestarting && r.restartDelay > 0) {
11527 // If waiting for a restart, then do nothing.
11528 return true;
11529 }
11530
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011531 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011532
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011533 // We are now bringing the service up, so no longer in the
11534 // restarting state.
11535 mRestartingServices.remove(r);
11536
Dianne Hackborne7f97212011-02-24 14:40:20 -080011537 // Service is now being launched, its package can't be stopped.
11538 try {
11539 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011540 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011541 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011542 } catch (IllegalArgumentException e) {
11543 Slog.w(TAG, "Failed trying to unstop package "
11544 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011545 }
11546
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011547 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011548 final String procName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011549 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011550
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011551 if (!isolated) {
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011552 app = getProcessRecordLocked(procName, r.appInfo.uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011553 if (DEBUG_MU)
11554 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11555 if (app != null && app.thread != null) {
11556 try {
11557 app.addPackage(r.appInfo.packageName);
11558 realStartServiceLocked(r, app);
11559 return true;
11560 } catch (RemoteException e) {
11561 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11562 }
11563
11564 // If a dead object exception was thrown -- fall through to
11565 // restart the application.
11566 }
11567 } else {
11568 // If this service runs in an isolated process, then each time
11569 // we call startProcessLocked() we will get a new isolated
11570 // process, starting another process if we are currently waiting
11571 // for a previous process to come up. To deal with this, we store
11572 // in the service any current isolated process it is running in or
11573 // waiting to have come up.
11574 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011575 }
11576
Dianne Hackborn36124872009-10-08 16:22:03 -070011577 // Not running -- get it started, and enqueue this service record
11578 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011579 if (app == null) {
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011580 if ((app=startProcessLocked(procName, r.appInfo, true, intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011581 "service", r.name, false, isolated)) == null) {
11582 Slog.w(TAG, "Unable to launch app "
11583 + r.appInfo.packageName + "/"
11584 + r.appInfo.uid + " for service "
11585 + r.intent.getIntent() + ": process is bad");
11586 bringDownServiceLocked(r, true);
11587 return false;
11588 }
11589 if (isolated) {
11590 r.isolatedProc = app;
11591 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011592 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011594 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011595 mPendingServices.add(r);
11596 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011598 return true;
11599 }
11600
11601 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011602 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011603 //r.dump(" ");
11604
11605 // Does it still need to run?
11606 if (!force && r.startRequested) {
11607 return;
11608 }
11609 if (r.connections.size() > 0) {
11610 if (!force) {
11611 // XXX should probably keep a count of the number of auto-create
11612 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011613 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011614 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011615 ArrayList<ConnectionRecord> cr = it.next();
11616 for (int i=0; i<cr.size(); i++) {
11617 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11618 return;
11619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011620 }
11621 }
11622 }
11623
11624 // Report to all of the connections that the service is no longer
11625 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011626 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011627 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011628 ArrayList<ConnectionRecord> c = it.next();
11629 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011630 ConnectionRecord cr = c.get(i);
11631 // There is still a connection to the service that is
11632 // being brought down. Mark it as dead.
11633 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011634 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011635 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011636 } catch (Exception e) {
11637 Slog.w(TAG, "Failure disconnecting service " + r.name +
11638 " to connection " + c.get(i).conn.asBinder() +
11639 " (in " + c.get(i).binding.client.processName + ")", e);
11640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011641 }
11642 }
11643 }
11644
11645 // Tell the service that it has been unbound.
11646 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11647 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11648 while (it.hasNext()) {
11649 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011650 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011651 + ": hasBound=" + ibr.hasBound);
11652 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11653 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011654 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011655 updateOomAdjLocked(r.app);
11656 ibr.hasBound = false;
11657 r.app.thread.scheduleUnbindService(r,
11658 ibr.intent.getIntent());
11659 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011660 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011661 + r.shortName, e);
11662 serviceDoneExecutingLocked(r, true);
11663 }
11664 }
11665 }
11666 }
11667
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011668 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011669 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011670 System.identityHashCode(r), r.shortName,
11671 (r.app != null) ? r.app.pid : -1);
11672
Amith Yamasani742a6712011-05-04 14:49:28 -070011673 mServiceMap.removeServiceByName(r.name, r.userId);
11674 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011675 r.totalRestartCount = 0;
11676 unscheduleServiceRestartLocked(r);
11677
11678 // Also make sure it is not on the pending list.
11679 int N = mPendingServices.size();
11680 for (int i=0; i<N; i++) {
11681 if (mPendingServices.get(i) == r) {
11682 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011683 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011684 i--;
11685 N--;
11686 }
11687 }
11688
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011689 r.cancelNotification();
11690 r.isForeground = false;
11691 r.foregroundId = 0;
11692 r.foregroundNoti = null;
11693
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011694 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011695 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011696 r.pendingStarts.clear();
11697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011698 if (r.app != null) {
11699 synchronized (r.stats.getBatteryStats()) {
11700 r.stats.stopLaunchedLocked();
11701 }
11702 r.app.services.remove(r);
11703 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011704 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011705 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011706 mStoppingServices.add(r);
11707 updateOomAdjLocked(r.app);
11708 r.app.thread.scheduleStopService(r);
11709 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011710 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011711 + r.shortName, e);
11712 serviceDoneExecutingLocked(r, true);
11713 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011714 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011715 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011716 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011717 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011718 }
11719 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011720 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011721 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011722 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011723
11724 if (r.bindings.size() > 0) {
11725 r.bindings.clear();
11726 }
11727
11728 if (r.restarter instanceof ServiceRestarter) {
11729 ((ServiceRestarter)r.restarter).setService(null);
11730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011731 }
11732
11733 ComponentName startServiceLocked(IApplicationThread caller,
11734 Intent service, String resolvedType,
11735 int callingPid, int callingUid) {
11736 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011737 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011738 + " type=" + resolvedType + " args=" + service.getExtras());
11739
11740 if (caller != null) {
11741 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11742 if (callerApp == null) {
11743 throw new SecurityException(
11744 "Unable to find app for caller " + caller
11745 + " (pid=" + Binder.getCallingPid()
11746 + ") when starting service " + service);
11747 }
11748 }
11749
11750 ServiceLookupResult res =
11751 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011752 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011753 if (res == null) {
11754 return null;
11755 }
11756 if (res.record == null) {
11757 return new ComponentName("!", res.permission != null
11758 ? res.permission : "private to package");
11759 }
11760 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011761 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11762 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011763 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011764 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011765 }
11766 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011767 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011768 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011769 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011770 r.lastActivity = SystemClock.uptimeMillis();
11771 synchronized (r.stats.getBatteryStats()) {
11772 r.stats.startRunningLocked();
11773 }
11774 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11775 return new ComponentName("!", "Service process is bad");
11776 }
11777 return r.name;
11778 }
11779 }
11780
11781 public ComponentName startService(IApplicationThread caller, Intent service,
11782 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011783 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011784 // Refuse possible leaked file descriptors
11785 if (service != null && service.hasFileDescriptors() == true) {
11786 throw new IllegalArgumentException("File descriptors passed in Intent");
11787 }
11788
Amith Yamasani742a6712011-05-04 14:49:28 -070011789 if (DEBUG_SERVICE)
11790 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011791 synchronized(this) {
11792 final int callingPid = Binder.getCallingPid();
11793 final int callingUid = Binder.getCallingUid();
11794 final long origId = Binder.clearCallingIdentity();
11795 ComponentName res = startServiceLocked(caller, service,
11796 resolvedType, callingPid, callingUid);
11797 Binder.restoreCallingIdentity(origId);
11798 return res;
11799 }
11800 }
11801
11802 ComponentName startServiceInPackage(int uid,
11803 Intent service, String resolvedType) {
11804 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011805 if (DEBUG_SERVICE)
11806 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011807 final long origId = Binder.clearCallingIdentity();
11808 ComponentName res = startServiceLocked(null, service,
11809 resolvedType, -1, uid);
11810 Binder.restoreCallingIdentity(origId);
11811 return res;
11812 }
11813 }
11814
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011815 private void stopServiceLocked(ServiceRecord service) {
11816 synchronized (service.stats.getBatteryStats()) {
11817 service.stats.stopRunningLocked();
11818 }
11819 service.startRequested = false;
11820 service.callStart = false;
11821 bringDownServiceLocked(service, false);
11822 }
11823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011824 public int stopService(IApplicationThread caller, Intent service,
11825 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011826 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011827 // Refuse possible leaked file descriptors
11828 if (service != null && service.hasFileDescriptors() == true) {
11829 throw new IllegalArgumentException("File descriptors passed in Intent");
11830 }
11831
11832 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011833 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011834 + " type=" + resolvedType);
11835
11836 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11837 if (caller != null && callerApp == null) {
11838 throw new SecurityException(
11839 "Unable to find app for caller " + caller
11840 + " (pid=" + Binder.getCallingPid()
11841 + ") when stopping service " + service);
11842 }
11843
11844 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011845 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11846 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011847 if (r != null) {
11848 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011849 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011850 try {
11851 stopServiceLocked(r.record);
11852 } finally {
11853 Binder.restoreCallingIdentity(origId);
11854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011855 return 1;
11856 }
11857 return -1;
11858 }
11859 }
11860
11861 return 0;
11862 }
11863
11864 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011865 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011866 // Refuse possible leaked file descriptors
11867 if (service != null && service.hasFileDescriptors() == true) {
11868 throw new IllegalArgumentException("File descriptors passed in Intent");
11869 }
11870
11871 IBinder ret = null;
11872
11873 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011874 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11875 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011876
11877 if (r != null) {
11878 // r.record is null if findServiceLocked() failed the caller permission check
11879 if (r.record == null) {
11880 throw new SecurityException(
11881 "Permission Denial: Accessing service " + r.record.name
11882 + " from pid=" + Binder.getCallingPid()
11883 + ", uid=" + Binder.getCallingUid()
11884 + " requires " + r.permission);
11885 }
11886 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11887 if (ib != null) {
11888 ret = ib.binder;
11889 }
11890 }
11891 }
11892
11893 return ret;
11894 }
11895
11896 public boolean stopServiceToken(ComponentName className, IBinder token,
11897 int startId) {
11898 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011899 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011900 + " " + token + " startId=" + startId);
11901 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011902 if (r != null) {
11903 if (startId >= 0) {
11904 // Asked to only stop if done with all work. Note that
11905 // to avoid leaks, we will take this as dropping all
11906 // start items up to and including this one.
11907 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11908 if (si != null) {
11909 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011910 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11911 cur.removeUriPermissionsLocked();
11912 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011913 break;
11914 }
11915 }
11916 }
11917
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011918 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011919 return false;
11920 }
11921
11922 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011923 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011924 + " is last, but have " + r.deliveredStarts.size()
11925 + " remaining args");
11926 }
11927 }
11928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011929 synchronized (r.stats.getBatteryStats()) {
11930 r.stats.stopRunningLocked();
11931 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011932 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011933 }
11934 final long origId = Binder.clearCallingIdentity();
11935 bringDownServiceLocked(r, false);
11936 Binder.restoreCallingIdentity(origId);
11937 return true;
11938 }
11939 }
11940 return false;
11941 }
11942
11943 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011944 int id, Notification notification, boolean removeNotification) {
11945 final long origId = Binder.clearCallingIdentity();
11946 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011947 synchronized(this) {
11948 ServiceRecord r = findServiceLocked(className, token);
11949 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011950 if (id != 0) {
11951 if (notification == null) {
11952 throw new IllegalArgumentException("null notification");
11953 }
11954 if (r.foregroundId != id) {
11955 r.cancelNotification();
11956 r.foregroundId = id;
11957 }
11958 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11959 r.foregroundNoti = notification;
11960 r.isForeground = true;
11961 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011962 if (r.app != null) {
11963 updateServiceForegroundLocked(r.app, true);
11964 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011965 } else {
11966 if (r.isForeground) {
11967 r.isForeground = false;
11968 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011969 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011970 updateServiceForegroundLocked(r.app, true);
11971 }
11972 }
11973 if (removeNotification) {
11974 r.cancelNotification();
11975 r.foregroundId = 0;
11976 r.foregroundNoti = null;
11977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011978 }
11979 }
11980 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011981 } finally {
11982 Binder.restoreCallingIdentity(origId);
11983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984 }
11985
11986 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11987 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011988 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011989 if (sr.isForeground) {
11990 anyForeground = true;
11991 break;
11992 }
11993 }
11994 if (anyForeground != proc.foregroundServices) {
11995 proc.foregroundServices = anyForeground;
11996 if (oomAdj) {
11997 updateOomAdjLocked();
11998 }
11999 }
12000 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070012001
12002 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo) {
12003 boolean result = false;
12004 if (UserId.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
12005 result = false;
12006 } else if (componentProcessName == aInfo.packageName) {
12007 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
12008 } else if ("system".equals(componentProcessName)) {
12009 result = true;
12010 }
12011 if (DEBUG_MU) {
12012 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo + ") = " + result);
12013 }
12014 return result;
12015 }
12016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012017 public int bindService(IApplicationThread caller, IBinder token,
12018 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080012019 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012020 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012021 // Refuse possible leaked file descriptors
12022 if (service != null && service.hasFileDescriptors() == true) {
12023 throw new IllegalArgumentException("File descriptors passed in Intent");
12024 }
12025
Amith Yamasani37ce3a82012-02-06 12:04:42 -080012026 checkValidCaller(Binder.getCallingUid(), userId);
12027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012028 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012029 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012030 + " type=" + resolvedType + " conn=" + connection.asBinder()
12031 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070012032 if (DEBUG_MU)
12033 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
12034 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012035 final ProcessRecord callerApp = getRecordForAppLocked(caller);
12036 if (callerApp == null) {
12037 throw new SecurityException(
12038 "Unable to find app for caller " + caller
12039 + " (pid=" + Binder.getCallingPid()
12040 + ") when binding service " + service);
12041 }
12042
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012043 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012044 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012045 activity = mMainStack.isInStackLocked(token);
12046 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012047 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012048 return 0;
12049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012050 }
12051
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012052 int clientLabel = 0;
12053 PendingIntent clientIntent = null;
12054
12055 if (callerApp.info.uid == Process.SYSTEM_UID) {
12056 // Hacky kind of thing -- allow system stuff to tell us
12057 // what they are, so we can report this elsewhere for
12058 // others to know why certain services are running.
12059 try {
12060 clientIntent = (PendingIntent)service.getParcelableExtra(
12061 Intent.EXTRA_CLIENT_INTENT);
12062 } catch (RuntimeException e) {
12063 }
12064 if (clientIntent != null) {
12065 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
12066 if (clientLabel != 0) {
12067 // There are no useful extras in the intent, trash them.
12068 // System code calling with this stuff just needs to know
12069 // this will happen.
12070 service = service.cloneFilter();
12071 }
12072 }
12073 }
12074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075 ServiceLookupResult res =
12076 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080012077 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012078 if (res == null) {
12079 return 0;
12080 }
12081 if (res.record == null) {
12082 return -1;
12083 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070012084 if (isSingleton(res.record.processName, res.record.appInfo)) {
12085 userId = 0;
12086 res = retrieveServiceLocked(service, resolvedType, Binder.getCallingPid(),
12087 Binder.getCallingUid(), 0);
12088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012089 ServiceRecord s = res.record;
12090
12091 final long origId = Binder.clearCallingIdentity();
12092
12093 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012094 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012095 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012096 }
12097
12098 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
12099 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012100 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012101
12102 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012103 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12104 if (clist == null) {
12105 clist = new ArrayList<ConnectionRecord>();
12106 s.connections.put(binder, clist);
12107 }
12108 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012109 b.connections.add(c);
12110 if (activity != null) {
12111 if (activity.connections == null) {
12112 activity.connections = new HashSet<ConnectionRecord>();
12113 }
12114 activity.connections.add(c);
12115 }
12116 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012117 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12118 b.client.hasAboveClient = true;
12119 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012120 clist = mServiceConnections.get(binder);
12121 if (clist == null) {
12122 clist = new ArrayList<ConnectionRecord>();
12123 mServiceConnections.put(binder, clist);
12124 }
12125 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012126
12127 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
12128 s.lastActivity = SystemClock.uptimeMillis();
12129 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
12130 return 0;
12131 }
12132 }
12133
12134 if (s.app != null) {
12135 // This could have made the service more important.
12136 updateOomAdjLocked(s.app);
12137 }
12138
Joe Onorato8a9b2202010-02-26 18:56:32 -080012139 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012140 + ": received=" + b.intent.received
12141 + " apps=" + b.intent.apps.size()
12142 + " doRebind=" + b.intent.doRebind);
12143
12144 if (s.app != null && b.intent.received) {
12145 // Service is already running, so we can immediately
12146 // publish the connection.
12147 try {
12148 c.conn.connected(s.name, b.intent.binder);
12149 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012150 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012151 + " to connection " + c.conn.asBinder()
12152 + " (in " + c.binding.client.processName + ")", e);
12153 }
12154
12155 // If this is the first app connected back to this binding,
12156 // and the service had previously asked to be told when
12157 // rebound, then do so.
12158 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
12159 requestServiceBindingLocked(s, b.intent, true);
12160 }
12161 } else if (!b.intent.requested) {
12162 requestServiceBindingLocked(s, b.intent, false);
12163 }
12164
12165 Binder.restoreCallingIdentity(origId);
12166 }
12167
12168 return 1;
12169 }
12170
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012171 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012172 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012173 IBinder binder = c.conn.asBinder();
12174 AppBindRecord b = c.binding;
12175 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012176 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12177 if (clist != null) {
12178 clist.remove(c);
12179 if (clist.size() == 0) {
12180 s.connections.remove(binder);
12181 }
12182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012183 b.connections.remove(c);
12184 if (c.activity != null && c.activity != skipAct) {
12185 if (c.activity.connections != null) {
12186 c.activity.connections.remove(c);
12187 }
12188 }
12189 if (b.client != skipApp) {
12190 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012191 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12192 b.client.updateHasAboveClientLocked();
12193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012194 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012195 clist = mServiceConnections.get(binder);
12196 if (clist != null) {
12197 clist.remove(c);
12198 if (clist.size() == 0) {
12199 mServiceConnections.remove(binder);
12200 }
12201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012202
12203 if (b.connections.size() == 0) {
12204 b.intent.apps.remove(b.client);
12205 }
12206
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012207 if (!c.serviceDead) {
12208 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
12209 + ": shouldUnbind=" + b.intent.hasBound);
12210 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
12211 && b.intent.hasBound) {
12212 try {
12213 bumpServiceExecutingLocked(s, "unbind");
12214 updateOomAdjLocked(s.app);
12215 b.intent.hasBound = false;
12216 // Assume the client doesn't want to know about a rebind;
12217 // we will deal with that later if it asks for one.
12218 b.intent.doRebind = false;
12219 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
12220 } catch (Exception e) {
12221 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
12222 serviceDoneExecutingLocked(s, true);
12223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012224 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012225
12226 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
12227 bringDownServiceLocked(s, false);
12228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012229 }
12230 }
12231
12232 public boolean unbindService(IServiceConnection connection) {
12233 synchronized (this) {
12234 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012235 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012236 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
12237 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012238 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012239 + connection.asBinder());
12240 return false;
12241 }
12242
12243 final long origId = Binder.clearCallingIdentity();
12244
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012245 while (clist.size() > 0) {
12246 ConnectionRecord r = clist.get(0);
12247 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012248
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012249 if (r.binding.service.app != null) {
12250 // This could have made the service less important.
12251 updateOomAdjLocked(r.binding.service.app);
12252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012253 }
12254
12255 Binder.restoreCallingIdentity(origId);
12256 }
12257
12258 return true;
12259 }
12260
12261 public void publishService(IBinder token, Intent intent, IBinder service) {
12262 // Refuse possible leaked file descriptors
12263 if (intent != null && intent.hasFileDescriptors() == true) {
12264 throw new IllegalArgumentException("File descriptors passed in Intent");
12265 }
12266
12267 synchronized(this) {
12268 if (!(token instanceof ServiceRecord)) {
12269 throw new IllegalArgumentException("Invalid service token");
12270 }
12271 ServiceRecord r = (ServiceRecord)token;
12272
12273 final long origId = Binder.clearCallingIdentity();
12274
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012275 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012276 + " " + intent + ": " + service);
12277 if (r != null) {
12278 Intent.FilterComparison filter
12279 = new Intent.FilterComparison(intent);
12280 IntentBindRecord b = r.bindings.get(filter);
12281 if (b != null && !b.received) {
12282 b.binder = service;
12283 b.requested = true;
12284 b.received = true;
12285 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012286 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012287 = r.connections.values().iterator();
12288 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012289 ArrayList<ConnectionRecord> clist = it.next();
12290 for (int i=0; i<clist.size(); i++) {
12291 ConnectionRecord c = clist.get(i);
12292 if (!filter.equals(c.binding.intent.intent)) {
12293 if (DEBUG_SERVICE) Slog.v(
12294 TAG, "Not publishing to: " + c);
12295 if (DEBUG_SERVICE) Slog.v(
12296 TAG, "Bound intent: " + c.binding.intent.intent);
12297 if (DEBUG_SERVICE) Slog.v(
12298 TAG, "Published intent: " + intent);
12299 continue;
12300 }
12301 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12302 try {
12303 c.conn.connected(r.name, service);
12304 } catch (Exception e) {
12305 Slog.w(TAG, "Failure sending service " + r.name +
12306 " to connection " + c.conn.asBinder() +
12307 " (in " + c.binding.client.processName + ")", e);
12308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012309 }
12310 }
12311 }
12312 }
12313
12314 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12315
12316 Binder.restoreCallingIdentity(origId);
12317 }
12318 }
12319 }
12320
12321 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12322 // Refuse possible leaked file descriptors
12323 if (intent != null && intent.hasFileDescriptors() == true) {
12324 throw new IllegalArgumentException("File descriptors passed in Intent");
12325 }
12326
12327 synchronized(this) {
12328 if (!(token instanceof ServiceRecord)) {
12329 throw new IllegalArgumentException("Invalid service token");
12330 }
12331 ServiceRecord r = (ServiceRecord)token;
12332
12333 final long origId = Binder.clearCallingIdentity();
12334
12335 if (r != null) {
12336 Intent.FilterComparison filter
12337 = new Intent.FilterComparison(intent);
12338 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012339 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012340 + " at " + b + ": apps="
12341 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012342
12343 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012344 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012345 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012346 // Applications have already bound since the last
12347 // unbind, so just rebind right here.
12348 requestServiceBindingLocked(r, b, true);
12349 } else {
12350 // Note to tell the service the next time there is
12351 // a new client.
12352 b.doRebind = true;
12353 }
12354 }
12355
Per Edelberg78f9fff2010-08-30 20:01:35 +020012356 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012357
12358 Binder.restoreCallingIdentity(origId);
12359 }
12360 }
12361 }
12362
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012363 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012364 synchronized(this) {
12365 if (!(token instanceof ServiceRecord)) {
12366 throw new IllegalArgumentException("Invalid service token");
12367 }
12368 ServiceRecord r = (ServiceRecord)token;
12369 boolean inStopping = mStoppingServices.contains(token);
12370 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012371 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012372 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012373 + " with incorrect token: given " + token
12374 + ", expected " + r);
12375 return;
12376 }
12377
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012378 if (type == 1) {
12379 // This is a call from a service start... take care of
12380 // book-keeping.
12381 r.callStart = true;
12382 switch (res) {
12383 case Service.START_STICKY_COMPATIBILITY:
12384 case Service.START_STICKY: {
12385 // We are done with the associated start arguments.
12386 r.findDeliveredStart(startId, true);
12387 // Don't stop if killed.
12388 r.stopIfKilled = false;
12389 break;
12390 }
12391 case Service.START_NOT_STICKY: {
12392 // We are done with the associated start arguments.
12393 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012394 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012395 // There is no more work, and this service
12396 // doesn't want to hang around if killed.
12397 r.stopIfKilled = true;
12398 }
12399 break;
12400 }
12401 case Service.START_REDELIVER_INTENT: {
12402 // We'll keep this item until they explicitly
12403 // call stop for it, but keep track of the fact
12404 // that it was delivered.
12405 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12406 if (si != null) {
12407 si.deliveryCount = 0;
12408 si.doneExecutingCount++;
12409 // Don't stop if killed.
12410 r.stopIfKilled = true;
12411 }
12412 break;
12413 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012414 case Service.START_TASK_REMOVED_COMPLETE: {
12415 // Special processing for onTaskRemoved(). Don't
12416 // impact normal onStartCommand() processing.
12417 r.findDeliveredStart(startId, true);
12418 break;
12419 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012420 default:
12421 throw new IllegalArgumentException(
12422 "Unknown service start result: " + res);
12423 }
12424 if (res == Service.START_STICKY_COMPATIBILITY) {
12425 r.callStart = false;
12426 }
12427 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012428 if (DEBUG_MU)
12429 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12430 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012431 final long origId = Binder.clearCallingIdentity();
12432 serviceDoneExecutingLocked(r, inStopping);
12433 Binder.restoreCallingIdentity(origId);
12434 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012435 Slog.w(TAG, "Done executing unknown service from pid "
12436 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012437 }
12438 }
12439 }
12440
12441 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012442 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12443 + ": nesting=" + r.executeNesting
12444 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012445 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012446 r.executeNesting--;
12447 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012448 if (DEBUG_SERVICE) Slog.v(TAG,
12449 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012450 r.app.executingServices.remove(r);
12451 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012452 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12453 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012454 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12455 }
12456 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012457 if (DEBUG_SERVICE) Slog.v(TAG,
12458 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012459 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012460 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012461 }
12462 updateOomAdjLocked(r.app);
12463 }
12464 }
12465
12466 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012467 String anrMessage = null;
12468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012469 synchronized(this) {
12470 if (proc.executingServices.size() == 0 || proc.thread == null) {
12471 return;
12472 }
12473 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12474 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12475 ServiceRecord timeout = null;
12476 long nextTime = 0;
12477 while (it.hasNext()) {
12478 ServiceRecord sr = it.next();
12479 if (sr.executingStart < maxTime) {
12480 timeout = sr;
12481 break;
12482 }
12483 if (sr.executingStart > nextTime) {
12484 nextTime = sr.executingStart;
12485 }
12486 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012487 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012488 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012489 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012490 } else {
12491 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12492 msg.obj = proc;
12493 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12494 }
12495 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012496
12497 if (anrMessage != null) {
12498 appNotResponding(proc, null, null, anrMessage);
12499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012500 }
12501
12502 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012503 // BACKUP AND RESTORE
12504 // =========================================================
12505
12506 // Cause the target app to be launched if necessary and its backup agent
12507 // instantiated. The backup agent will invoke backupAgentCreated() on the
12508 // activity manager to announce its creation.
12509 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012510 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012511 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12512
12513 synchronized(this) {
12514 // !!! TODO: currently no check here that we're already bound
12515 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12516 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12517 synchronized (stats) {
12518 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12519 }
12520
Dianne Hackborne7f97212011-02-24 14:40:20 -080012521 // Backup agent is now in use, its package can't be stopped.
12522 try {
12523 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012524 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012525 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012526 } catch (IllegalArgumentException e) {
12527 Slog.w(TAG, "Failed trying to unstop package "
12528 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012529 }
12530
Christopher Tate181fafa2009-05-14 11:12:14 -070012531 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012532 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12533 ? new ComponentName(app.packageName, app.backupAgentName)
12534 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012535 // startProcessLocked() returns existing proc's record if it's already running
12536 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012537 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012538 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012539 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012540 return false;
12541 }
12542
12543 r.app = proc;
12544 mBackupTarget = r;
12545 mBackupAppName = app.packageName;
12546
Christopher Tate6fa95972009-06-05 18:43:55 -070012547 // Try not to kill the process during backup
12548 updateOomAdjLocked(proc);
12549
Christopher Tate181fafa2009-05-14 11:12:14 -070012550 // If the process is already attached, schedule the creation of the backup agent now.
12551 // If it is not yet live, this will be done when it attaches to the framework.
12552 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012553 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012554 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012555 proc.thread.scheduleCreateBackupAgent(app,
12556 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012557 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012558 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012559 }
12560 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012561 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012562 }
12563 // Invariants: at this point, the target app process exists and the application
12564 // is either already running or in the process of coming up. mBackupTarget and
12565 // mBackupAppName describe the app, so that when it binds back to the AM we
12566 // know that it's scheduled for a backup-agent operation.
12567 }
12568
12569 return true;
12570 }
12571
12572 // A backup agent has just come up
12573 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012574 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012575 + " = " + agent);
12576
12577 synchronized(this) {
12578 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012579 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012580 return;
12581 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012582 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012583
Dianne Hackborn06740692010-09-22 22:46:21 -070012584 long oldIdent = Binder.clearCallingIdentity();
12585 try {
12586 IBackupManager bm = IBackupManager.Stub.asInterface(
12587 ServiceManager.getService(Context.BACKUP_SERVICE));
12588 bm.agentConnected(agentPackageName, agent);
12589 } catch (RemoteException e) {
12590 // can't happen; the backup manager service is local
12591 } catch (Exception e) {
12592 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12593 e.printStackTrace();
12594 } finally {
12595 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012596 }
12597 }
12598
12599 // done with this agent
12600 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012601 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012602 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012603 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012604 return;
12605 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012606
12607 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012608 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012609 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012610 return;
12611 }
12612
Christopher Tate181fafa2009-05-14 11:12:14 -070012613 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012614 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012615 return;
12616 }
12617
Christopher Tate6fa95972009-06-05 18:43:55 -070012618 ProcessRecord proc = mBackupTarget.app;
12619 mBackupTarget = null;
12620 mBackupAppName = null;
12621
12622 // Not backing this app up any more; reset its OOM adjustment
12623 updateOomAdjLocked(proc);
12624
Christopher Tatec7b31e32009-06-10 15:49:30 -070012625 // If the app crashed during backup, 'thread' will be null here
12626 if (proc.thread != null) {
12627 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012628 proc.thread.scheduleDestroyBackupAgent(appInfo,
12629 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012630 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012631 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012632 e.printStackTrace();
12633 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012634 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012635 }
12636 }
12637 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012638 // BROADCASTS
12639 // =========================================================
12640
Josh Bartel7f208742010-02-25 11:01:44 -060012641 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012642 List cur) {
12643 final ContentResolver resolver = mContext.getContentResolver();
12644 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12645 if (list == null) {
12646 return cur;
12647 }
12648 int N = list.size();
12649 for (int i=0; i<N; i++) {
12650 Intent intent = list.get(i);
12651 if (filter.match(resolver, intent, true, TAG) >= 0) {
12652 if (cur == null) {
12653 cur = new ArrayList<Intent>();
12654 }
12655 cur.add(intent);
12656 }
12657 }
12658 return cur;
12659 }
12660
Christopher Tatef46723b2012-01-26 14:19:24 -080012661 boolean isPendingBroadcastProcessLocked(int pid) {
12662 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12663 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012665
Christopher Tatef46723b2012-01-26 14:19:24 -080012666 void skipPendingBroadcastLocked(int pid) {
12667 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12668 for (BroadcastQueue queue : mBroadcastQueues) {
12669 queue.skipPendingBroadcastLocked(pid);
12670 }
12671 }
12672
12673 // The app just attached; send any pending broadcasts that it should receive
12674 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12675 boolean didSomething = false;
12676 for (BroadcastQueue queue : mBroadcastQueues) {
12677 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012678 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012679 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012680 }
12681
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012682 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012683 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012684 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070012685 int callingUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012686 synchronized(this) {
12687 ProcessRecord callerApp = null;
12688 if (caller != null) {
12689 callerApp = getRecordForAppLocked(caller);
12690 if (callerApp == null) {
12691 throw new SecurityException(
12692 "Unable to find app for caller " + caller
12693 + " (pid=" + Binder.getCallingPid()
12694 + ") when registering receiver " + receiver);
12695 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012696 if (callerApp.info.uid != Process.SYSTEM_UID &&
12697 !callerApp.pkgList.contains(callerPackage)) {
12698 throw new SecurityException("Given caller package " + callerPackage
12699 + " is not running in process " + callerApp);
12700 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070012701 callingUid = callerApp.info.uid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012702 } else {
12703 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070012704 callingUid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012705 }
12706
12707 List allSticky = null;
12708
12709 // Look for any matching sticky broadcasts...
12710 Iterator actions = filter.actionsIterator();
12711 if (actions != null) {
12712 while (actions.hasNext()) {
12713 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012714 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012715 }
12716 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012717 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012718 }
12719
12720 // The first sticky in the list is returned directly back to
12721 // the client.
12722 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12723
Joe Onorato8a9b2202010-02-26 18:56:32 -080012724 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012725 + ": " + sticky);
12726
12727 if (receiver == null) {
12728 return sticky;
12729 }
12730
12731 ReceiverList rl
12732 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12733 if (rl == null) {
12734 rl = new ReceiverList(this, callerApp,
12735 Binder.getCallingPid(),
12736 Binder.getCallingUid(), receiver);
12737 if (rl.app != null) {
12738 rl.app.receivers.add(rl);
12739 } else {
12740 try {
12741 receiver.asBinder().linkToDeath(rl, 0);
12742 } catch (RemoteException e) {
12743 return sticky;
12744 }
12745 rl.linkedToDeath = true;
12746 }
12747 mRegisteredReceivers.put(receiver.asBinder(), rl);
12748 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070012749 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
12750 permission, callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012751 rl.add(bf);
12752 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012753 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012754 }
12755 mReceiverResolver.addFilter(bf);
12756
12757 // Enqueue broadcasts for all existing stickies that match
12758 // this filter.
12759 if (allSticky != null) {
12760 ArrayList receivers = new ArrayList();
12761 receivers.add(bf);
12762
12763 int N = allSticky.size();
12764 for (int i=0; i<N; i++) {
12765 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012766 BroadcastQueue queue = broadcastQueueForIntent(intent);
12767 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012768 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070012769 false, true, true, false);
Christopher Tatef46723b2012-01-26 14:19:24 -080012770 queue.enqueueParallelBroadcastLocked(r);
12771 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012772 }
12773 }
12774
12775 return sticky;
12776 }
12777 }
12778
12779 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012780 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012781
Christopher Tatef46723b2012-01-26 14:19:24 -080012782 final long origId = Binder.clearCallingIdentity();
12783 try {
12784 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012785
Christopher Tatef46723b2012-01-26 14:19:24 -080012786 synchronized(this) {
12787 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012788 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012789 if (rl != null) {
12790 if (rl.curBroadcast != null) {
12791 BroadcastRecord r = rl.curBroadcast;
12792 final boolean doNext = finishReceiverLocked(
12793 receiver.asBinder(), r.resultCode, r.resultData,
12794 r.resultExtras, r.resultAbort, true);
12795 if (doNext) {
12796 doTrim = true;
12797 r.queue.processNextBroadcast(false);
12798 }
12799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012800
Christopher Tatef46723b2012-01-26 14:19:24 -080012801 if (rl.app != null) {
12802 rl.app.receivers.remove(rl);
12803 }
12804 removeReceiverLocked(rl);
12805 if (rl.linkedToDeath) {
12806 rl.linkedToDeath = false;
12807 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012809 }
12810 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012811
Christopher Tatef46723b2012-01-26 14:19:24 -080012812 // If we actually concluded any broadcasts, we might now be able
12813 // to trim the recipients' apps from our working set
12814 if (doTrim) {
12815 trimApplications();
12816 return;
12817 }
12818
12819 } finally {
12820 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012822 }
12823
12824 void removeReceiverLocked(ReceiverList rl) {
12825 mRegisteredReceivers.remove(rl.receiver.asBinder());
12826 int N = rl.size();
12827 for (int i=0; i<N; i++) {
12828 mReceiverResolver.removeFilter(rl.get(i));
12829 }
12830 }
12831
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012832 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12833 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12834 ProcessRecord r = mLruProcesses.get(i);
12835 if (r.thread != null) {
12836 try {
12837 r.thread.dispatchPackageBroadcast(cmd, packages);
12838 } catch (RemoteException ex) {
12839 }
12840 }
12841 }
12842 }
12843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012844 private final int broadcastIntentLocked(ProcessRecord callerApp,
12845 String callerPackage, Intent intent, String resolvedType,
12846 IIntentReceiver resultTo, int resultCode, String resultData,
12847 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012848 boolean ordered, boolean sticky, int callingPid, int callingUid,
12849 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012850 intent = new Intent(intent);
12851
Dianne Hackborne7f97212011-02-24 14:40:20 -080012852 // By default broadcasts do not go to stopped apps.
12853 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12854
Joe Onorato8a9b2202010-02-26 18:56:32 -080012855 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012856 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012857 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012858 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012859 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012860 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070012861
12862 boolean onlySendToCaller = false;
12863
12864 // If the caller is trying to send this broadcast to a different
12865 // user, verify that is allowed.
12866 if (UserId.getUserId(callingUid) != userId) {
12867 if (checkComponentPermission(
12868 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
12869 callingPid, callingUid, -1, true)
12870 != PackageManager.PERMISSION_GRANTED) {
12871 if (checkComponentPermission(
12872 android.Manifest.permission.INTERACT_ACROSS_USERS,
12873 callingPid, callingUid, -1, true)
12874 == PackageManager.PERMISSION_GRANTED) {
12875 onlySendToCaller = true;
12876 } else {
12877 String msg = "Permission Denial: " + intent.getAction()
12878 + " broadcast from " + callerPackage
12879 + " asks to send as user " + userId
12880 + " but is calling from user " + UserId.getUserId(callingUid)
12881 + "; this requires "
12882 + android.Manifest.permission.INTERACT_ACROSS_USERS;
12883 Slog.w(TAG, msg);
12884 throw new SecurityException(msg);
12885 }
12886 }
12887 }
12888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012889 // Handle special intents: if this broadcast is from the package
12890 // manager about a package being removed, we need to remove all of
12891 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012892 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012893 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012894 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12895 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012896 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012897 || uidRemoved) {
12898 if (checkComponentPermission(
12899 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012900 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012901 == PackageManager.PERMISSION_GRANTED) {
12902 if (uidRemoved) {
12903 final Bundle intentExtras = intent.getExtras();
12904 final int uid = intentExtras != null
12905 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12906 if (uid >= 0) {
12907 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12908 synchronized (bs) {
12909 bs.removeUidStatsLocked(uid);
12910 }
12911 }
12912 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012913 // If resources are unvailble just force stop all
12914 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012915 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012916 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12917 if (list != null && (list.length > 0)) {
12918 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012919 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012920 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012921 sendPackageBroadcastLocked(
12922 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012923 }
12924 } else {
12925 Uri data = intent.getData();
12926 String ssp;
12927 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12928 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12929 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012930 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12931 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012932 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012933 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012934 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12935 new String[] {ssp});
12936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012937 }
12938 }
12939 }
12940 } else {
12941 String msg = "Permission Denial: " + intent.getAction()
12942 + " broadcast from " + callerPackage + " (pid=" + callingPid
12943 + ", uid=" + callingUid + ")"
12944 + " requires "
12945 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012946 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012947 throw new SecurityException(msg);
12948 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012949
12950 // Special case for adding a package: by default turn on compatibility
12951 // mode.
12952 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012953 Uri data = intent.getData();
12954 String ssp;
12955 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12956 mCompatModePackages.handlePackageAddedLocked(ssp,
12957 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012959 }
12960
12961 /*
12962 * If this is the time zone changed action, queue up a message that will reset the timezone
12963 * of all currently running processes. This message will get queued up before the broadcast
12964 * happens.
12965 */
12966 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12967 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12968 }
12969
Robert Greenwalt03595d02010-11-02 14:08:23 -070012970 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12971 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12972 }
12973
Robert Greenwalt434203a2010-10-11 16:00:27 -070012974 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12975 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12976 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12977 }
12978
Dianne Hackborn854060af2009-07-09 18:14:31 -070012979 /*
12980 * Prevent non-system code (defined here to be non-persistent
12981 * processes) from sending protected broadcasts.
12982 */
12983 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
fredc0f420372012-04-12 00:02:00 -070012984 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
12985 callingUid == 0) {
Dianne Hackborn854060af2009-07-09 18:14:31 -070012986 // Always okay.
12987 } else if (callerApp == null || !callerApp.persistent) {
12988 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012989 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012990 intent.getAction())) {
12991 String msg = "Permission Denial: not allowed to send broadcast "
12992 + intent.getAction() + " from pid="
12993 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012994 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012995 throw new SecurityException(msg);
12996 }
12997 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012998 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012999 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070013000 }
13001 }
13002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013003 // Add to the sticky list if requested.
13004 if (sticky) {
13005 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
13006 callingPid, callingUid)
13007 != PackageManager.PERMISSION_GRANTED) {
13008 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
13009 + callingPid + ", uid=" + callingUid
13010 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013011 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013012 throw new SecurityException(msg);
13013 }
13014 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013015 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013016 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070013017 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013018 }
13019 if (intent.getComponent() != null) {
13020 throw new SecurityException(
13021 "Sticky broadcasts can't target a specific component");
13022 }
13023 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13024 if (list == null) {
13025 list = new ArrayList<Intent>();
13026 mStickyBroadcasts.put(intent.getAction(), list);
13027 }
13028 int N = list.size();
13029 int i;
13030 for (i=0; i<N; i++) {
13031 if (intent.filterEquals(list.get(i))) {
13032 // This sticky already exists, replace it.
13033 list.set(i, new Intent(intent));
13034 break;
13035 }
13036 }
13037 if (i >= N) {
13038 list.add(new Intent(intent));
13039 }
13040 }
13041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013042 // Figure out who all will receive this broadcast.
13043 List receivers = null;
13044 List<BroadcastFilter> registeredReceivers = null;
13045 try {
13046 if (intent.getComponent() != null) {
13047 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013048 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070013049 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013050 if (ai != null) {
13051 receivers = new ArrayList();
13052 ResolveInfo ri = new ResolveInfo();
Amith Yamasania4a54e22012-04-16 15:44:19 -070013053 if (isSingleton(ai.processName, ai.applicationInfo)) {
13054 ri.activityInfo = getActivityInfoForUser(ai, 0);
13055 } else {
13056 ri.activityInfo = getActivityInfoForUser(ai, userId);
13057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013058 receivers.add(ri);
13059 }
13060 } else {
13061 // Need to resolve the intent to interested receivers...
13062 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
13063 == 0) {
13064 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013065 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070013066 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013067 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070013068 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
13069 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013070 }
13071 } catch (RemoteException ex) {
13072 // pm is in same process, this will never happen.
13073 }
13074
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013075 final boolean replacePending =
13076 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
13077
Joe Onorato8a9b2202010-02-26 18:56:32 -080013078 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013079 + " replacePending=" + replacePending);
13080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013081 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
13082 if (!ordered && NR > 0) {
13083 // If we are not serializing this broadcast, then send the
13084 // registered receivers separately so they don't wait for the
13085 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080013086 final BroadcastQueue queue = broadcastQueueForIntent(intent);
13087 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013088 callerPackage, callingPid, callingUid, requiredPermission,
13089 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070013090 ordered, sticky, false, onlySendToCaller);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013091 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080013092 TAG, "Enqueueing parallel broadcast " + r);
13093 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013094 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013095 queue.enqueueParallelBroadcastLocked(r);
13096 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013097 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013098 registeredReceivers = null;
13099 NR = 0;
13100 }
13101
13102 // Merge into one list.
13103 int ir = 0;
13104 if (receivers != null) {
13105 // A special case for PACKAGE_ADDED: do not allow the package
13106 // being added to see this broadcast. This prevents them from
13107 // using this as a back door to get run as soon as they are
13108 // installed. Maybe in the future we want to have a special install
13109 // broadcast or such for apps, but we'd like to deliberately make
13110 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013111 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013112 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
13113 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
13114 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013115 Uri data = intent.getData();
13116 if (data != null) {
13117 String pkgName = data.getSchemeSpecificPart();
13118 if (pkgName != null) {
13119 skipPackages = new String[] { pkgName };
13120 }
13121 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013122 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013123 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070013124 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013125 if (skipPackages != null && (skipPackages.length > 0)) {
13126 for (String skipPackage : skipPackages) {
13127 if (skipPackage != null) {
13128 int NT = receivers.size();
13129 for (int it=0; it<NT; it++) {
13130 ResolveInfo curt = (ResolveInfo)receivers.get(it);
13131 if (curt.activityInfo.packageName.equals(skipPackage)) {
13132 receivers.remove(it);
13133 it--;
13134 NT--;
13135 }
13136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013137 }
13138 }
13139 }
13140
13141 int NT = receivers != null ? receivers.size() : 0;
13142 int it = 0;
13143 ResolveInfo curt = null;
13144 BroadcastFilter curr = null;
13145 while (it < NT && ir < NR) {
13146 if (curt == null) {
13147 curt = (ResolveInfo)receivers.get(it);
13148 }
13149 if (curr == null) {
13150 curr = registeredReceivers.get(ir);
13151 }
13152 if (curr.getPriority() >= curt.priority) {
13153 // Insert this broadcast record into the final list.
13154 receivers.add(it, curr);
13155 ir++;
13156 curr = null;
13157 it++;
13158 NT++;
13159 } else {
13160 // Skip to the next ResolveInfo in the final list.
13161 it++;
13162 curt = null;
13163 }
13164 }
13165 }
13166 while (ir < NR) {
13167 if (receivers == null) {
13168 receivers = new ArrayList();
13169 }
13170 receivers.add(registeredReceivers.get(ir));
13171 ir++;
13172 }
13173
13174 if ((receivers != null && receivers.size() > 0)
13175 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013176 BroadcastQueue queue = broadcastQueueForIntent(intent);
13177 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013178 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013179 receivers, resultTo, resultCode, resultData, map, ordered,
Dianne Hackbornb4163a62012-08-02 18:31:26 -070013180 sticky, false, onlySendToCaller);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013181 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013182 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080013183 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013184 if (DEBUG_BROADCAST) {
13185 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013186 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013187 }
Christopher Tatef46723b2012-01-26 14:19:24 -080013188 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013189 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013190 queue.enqueueOrderedBroadcastLocked(r);
13191 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013193 }
13194
Dianne Hackborna4972e92012-03-14 10:38:05 -070013195 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013196 }
13197
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013198 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013199 // Refuse possible leaked file descriptors
13200 if (intent != null && intent.hasFileDescriptors() == true) {
13201 throw new IllegalArgumentException("File descriptors passed in Intent");
13202 }
13203
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013204 int flags = intent.getFlags();
13205
13206 if (!mProcessesReady) {
13207 // if the caller really truly claims to know what they're doing, go
13208 // ahead and allow the broadcast without launching any receivers
13209 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
13210 intent = new Intent(intent);
13211 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
13212 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
13213 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
13214 + " before boot completion");
13215 throw new IllegalStateException("Cannot broadcast before boot completed");
13216 }
13217 }
13218
13219 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
13220 throw new IllegalArgumentException(
13221 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
13222 }
13223
13224 return intent;
13225 }
13226
13227 public final int broadcastIntent(IApplicationThread caller,
13228 Intent intent, String resolvedType, IIntentReceiver resultTo,
13229 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013230 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013231 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013232 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013233 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070013234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013235 final ProcessRecord callerApp = getRecordForAppLocked(caller);
13236 final int callingPid = Binder.getCallingPid();
13237 final int callingUid = Binder.getCallingUid();
13238 final long origId = Binder.clearCallingIdentity();
13239 int res = broadcastIntentLocked(callerApp,
13240 callerApp != null ? callerApp.info.packageName : null,
13241 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070013242 resultCode, resultData, map, requiredPermission, serialized, sticky,
13243 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013244 Binder.restoreCallingIdentity(origId);
13245 return res;
13246 }
13247 }
13248
13249 int broadcastIntentInPackage(String packageName, int uid,
13250 Intent intent, String resolvedType, IIntentReceiver resultTo,
13251 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013252 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013253 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013254 intent = verifyBroadcastLocked(intent);
13255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013256 final long origId = Binder.clearCallingIdentity();
13257 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
13258 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013259 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013260 Binder.restoreCallingIdentity(origId);
13261 return res;
13262 }
13263 }
13264
Amith Yamasani742a6712011-05-04 14:49:28 -070013265 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
13266 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013267 // Refuse possible leaked file descriptors
13268 if (intent != null && intent.hasFileDescriptors() == true) {
13269 throw new IllegalArgumentException("File descriptors passed in Intent");
13270 }
13271
13272 synchronized(this) {
13273 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13274 != PackageManager.PERMISSION_GRANTED) {
13275 String msg = "Permission Denial: unbroadcastIntent() from pid="
13276 + Binder.getCallingPid()
13277 + ", uid=" + Binder.getCallingUid()
13278 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013279 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013280 throw new SecurityException(msg);
13281 }
13282 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13283 if (list != null) {
13284 int N = list.size();
13285 int i;
13286 for (i=0; i<N; i++) {
13287 if (intent.filterEquals(list.get(i))) {
13288 list.remove(i);
13289 break;
13290 }
13291 }
13292 }
13293 }
13294 }
13295
13296 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13297 String resultData, Bundle resultExtras, boolean resultAbort,
13298 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013299 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13300 if (r == null) {
13301 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013302 return false;
13303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013304
Christopher Tatef46723b2012-01-26 14:19:24 -080013305 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13306 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013307 }
13308
13309 public void finishReceiver(IBinder who, int resultCode, String resultData,
13310 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013311 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013312
13313 // Refuse possible leaked file descriptors
13314 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13315 throw new IllegalArgumentException("File descriptors passed in Bundle");
13316 }
13317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013318 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013319 try {
13320 boolean doNext = false;
13321 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013322
Christopher Tatef46723b2012-01-26 14:19:24 -080013323 synchronized(this) {
13324 r = broadcastRecordForReceiverLocked(who);
13325 if (r != null) {
13326 doNext = r.queue.finishReceiverLocked(r, resultCode,
13327 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013329 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013330
Christopher Tatef46723b2012-01-26 14:19:24 -080013331 if (doNext) {
13332 r.queue.processNextBroadcast(false);
13333 }
13334 trimApplications();
13335 } finally {
13336 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013340 // =========================================================
13341 // INSTRUMENTATION
13342 // =========================================================
13343
13344 public boolean startInstrumentation(ComponentName className,
13345 String profileFile, int flags, Bundle arguments,
13346 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013347 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013348 // Refuse possible leaked file descriptors
13349 if (arguments != null && arguments.hasFileDescriptors()) {
13350 throw new IllegalArgumentException("File descriptors passed in Bundle");
13351 }
13352
13353 synchronized(this) {
13354 InstrumentationInfo ii = null;
13355 ApplicationInfo ai = null;
13356 try {
13357 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013358 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013359 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070013360 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013361 } catch (PackageManager.NameNotFoundException e) {
13362 }
13363 if (ii == null) {
13364 reportStartInstrumentationFailure(watcher, className,
13365 "Unable to find instrumentation info for: " + className);
13366 return false;
13367 }
13368 if (ai == null) {
13369 reportStartInstrumentationFailure(watcher, className,
13370 "Unable to find instrumentation target package: " + ii.targetPackage);
13371 return false;
13372 }
13373
13374 int match = mContext.getPackageManager().checkSignatures(
13375 ii.targetPackage, ii.packageName);
13376 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13377 String msg = "Permission Denial: starting instrumentation "
13378 + className + " from pid="
13379 + Binder.getCallingPid()
13380 + ", uid=" + Binder.getCallingPid()
13381 + " not allowed because package " + ii.packageName
13382 + " does not have a signature matching the target "
13383 + ii.targetPackage;
13384 reportStartInstrumentationFailure(watcher, className, msg);
13385 throw new SecurityException(msg);
13386 }
13387
Amith Yamasani483f3b02012-03-13 16:08:00 -070013388 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013389 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013390 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013391 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013392 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013393 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013394 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013395 app.instrumentationProfileFile = profileFile;
13396 app.instrumentationArguments = arguments;
13397 app.instrumentationWatcher = watcher;
13398 app.instrumentationResultClass = className;
13399 Binder.restoreCallingIdentity(origId);
13400 }
13401
13402 return true;
13403 }
13404
13405 /**
13406 * Report errors that occur while attempting to start Instrumentation. Always writes the
13407 * error to the logs, but if somebody is watching, send the report there too. This enables
13408 * the "am" command to report errors with more information.
13409 *
13410 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13411 * @param cn The component name of the instrumentation.
13412 * @param report The error report.
13413 */
13414 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13415 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013416 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013417 try {
13418 if (watcher != null) {
13419 Bundle results = new Bundle();
13420 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13421 results.putString("Error", report);
13422 watcher.instrumentationStatus(cn, -1, results);
13423 }
13424 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013425 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013426 }
13427 }
13428
13429 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13430 if (app.instrumentationWatcher != null) {
13431 try {
13432 // NOTE: IInstrumentationWatcher *must* be oneway here
13433 app.instrumentationWatcher.instrumentationFinished(
13434 app.instrumentationClass,
13435 resultCode,
13436 results);
13437 } catch (RemoteException e) {
13438 }
13439 }
13440 app.instrumentationWatcher = null;
13441 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013442 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013443 app.instrumentationProfileFile = null;
13444 app.instrumentationArguments = null;
13445
Amith Yamasani483f3b02012-03-13 16:08:00 -070013446 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013447 }
13448
13449 public void finishInstrumentation(IApplicationThread target,
13450 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013451 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013452 // Refuse possible leaked file descriptors
13453 if (results != null && results.hasFileDescriptors()) {
13454 throw new IllegalArgumentException("File descriptors passed in Intent");
13455 }
13456
13457 synchronized(this) {
13458 ProcessRecord app = getRecordForAppLocked(target);
13459 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013460 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013461 return;
13462 }
13463 final long origId = Binder.clearCallingIdentity();
13464 finishInstrumentationLocked(app, resultCode, results);
13465 Binder.restoreCallingIdentity(origId);
13466 }
13467 }
13468
13469 // =========================================================
13470 // CONFIGURATION
13471 // =========================================================
13472
13473 public ConfigurationInfo getDeviceConfigurationInfo() {
13474 ConfigurationInfo config = new ConfigurationInfo();
13475 synchronized (this) {
13476 config.reqTouchScreen = mConfiguration.touchscreen;
13477 config.reqKeyboardType = mConfiguration.keyboard;
13478 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013479 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13480 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013481 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13482 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013483 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13484 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013485 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13486 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013487 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013488 }
13489 return config;
13490 }
13491
13492 public Configuration getConfiguration() {
13493 Configuration ci;
13494 synchronized(this) {
13495 ci = new Configuration(mConfiguration);
13496 }
13497 return ci;
13498 }
13499
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013500 public void updatePersistentConfiguration(Configuration values) {
13501 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13502 "updateConfiguration()");
13503 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13504 "updateConfiguration()");
13505 if (values == null) {
13506 throw new NullPointerException("Configuration must not be null");
13507 }
13508
13509 synchronized(this) {
13510 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013511 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013512 Binder.restoreCallingIdentity(origId);
13513 }
13514 }
13515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013516 public void updateConfiguration(Configuration values) {
13517 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13518 "updateConfiguration()");
13519
13520 synchronized(this) {
13521 if (values == null && mWindowManager != null) {
13522 // sentinel: fetch the current configuration from the window manager
13523 values = mWindowManager.computeNewConfiguration();
13524 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013525
13526 if (mWindowManager != null) {
13527 mProcessList.applyDisplaySize(mWindowManager);
13528 }
13529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013530 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013531 if (values != null) {
13532 Settings.System.clearConfiguration(values);
13533 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013534 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013535 Binder.restoreCallingIdentity(origId);
13536 }
13537 }
13538
13539 /**
13540 * Do either or both things: (1) change the current configuration, and (2)
13541 * make sure the given activity is running with the (now) current
13542 * configuration. Returns true if the activity has been left running, or
13543 * false if <var>starting</var> is being destroyed to match the new
13544 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013545 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013546 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013547 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013548 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013549 // do nothing if we are headless
13550 if (mHeadless) return true;
13551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013552 int changes = 0;
13553
13554 boolean kept = true;
13555
13556 if (values != null) {
13557 Configuration newConfig = new Configuration(mConfiguration);
13558 changes = newConfig.updateFrom(values);
13559 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013560 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013561 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013562 }
13563
Doug Zongker2bec3d42009-12-04 12:52:44 -080013564 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013565
Dianne Hackborn813075a62011-11-14 17:45:19 -080013566 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013567 saveLocaleLocked(values.locale,
13568 !values.locale.equals(mConfiguration.locale),
13569 values.userSetLocale);
13570 }
13571
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013572 mConfigurationSeq++;
13573 if (mConfigurationSeq <= 0) {
13574 mConfigurationSeq = 1;
13575 }
13576 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013577 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013578 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013579
13580 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013581
13582 // TODO: If our config changes, should we auto dismiss any currently
13583 // showing dialogs?
13584 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013585
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013586 AttributeCache ac = AttributeCache.instance();
13587 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013588 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013590
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013591 // Make sure all resources in our process are updated
13592 // right now, so that anyone who is going to retrieve
13593 // resource values after we return will be sure to get
13594 // the new ones. This is especially important during
13595 // boot, where the first config change needs to guarantee
13596 // all resources have that config before following boot
13597 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013598 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013599
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013600 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013601 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013602 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013603 mHandler.sendMessage(msg);
13604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013605
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013606 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13607 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 try {
13609 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013610 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013611 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013612 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013613 }
13614 } catch (Exception e) {
13615 }
13616 }
13617 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013618 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13619 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013620 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013621 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013622 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13623 broadcastIntentLocked(null, null,
13624 new Intent(Intent.ACTION_LOCALE_CHANGED),
13625 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013626 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013628 }
13629 }
13630
13631 if (changes != 0 && starting == null) {
13632 // If the configuration changed, and the caller is not already
13633 // in the process of starting an activity, then find the top
13634 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013635 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013636 }
13637
13638 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013639 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013640 // And we need to make sure at this point that all other activities
13641 // are made visible with the correct configuration.
13642 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013643 }
13644
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013645 if (values != null && mWindowManager != null) {
13646 mWindowManager.setNewConfiguration(mConfiguration);
13647 }
13648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013649 return kept;
13650 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013651
13652 /**
13653 * Decide based on the configuration whether we should shouw the ANR,
13654 * crash, etc dialogs. The idea is that if there is no affordnace to
13655 * press the on-screen buttons, we shouldn't show the dialog.
13656 *
13657 * A thought: SystemUI might also want to get told about this, the Power
13658 * dialog / global actions also might want different behaviors.
13659 */
13660 private static final boolean shouldShowDialogs(Configuration config) {
13661 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13662 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013664
13665 /**
13666 * Save the locale. You must be inside a synchronized (this) block.
13667 */
13668 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13669 if(isDiff) {
13670 SystemProperties.set("user.language", l.getLanguage());
13671 SystemProperties.set("user.region", l.getCountry());
13672 }
13673
13674 if(isPersist) {
13675 SystemProperties.set("persist.sys.language", l.getLanguage());
13676 SystemProperties.set("persist.sys.country", l.getCountry());
13677 SystemProperties.set("persist.sys.localevar", l.getVariant());
13678 }
13679 }
13680
Adam Powelldd8fab22012-03-22 17:47:27 -070013681 @Override
13682 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13683 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013684 return srec != null && srec.task.affinity != null &&
13685 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070013686 }
13687
13688 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13689 Intent resultData) {
13690 ComponentName dest = destIntent.getComponent();
13691
13692 synchronized (this) {
13693 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013694 if (srec == null) {
13695 return false;
13696 }
Adam Powelldd8fab22012-03-22 17:47:27 -070013697 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13698 final int start = history.indexOf(srec);
13699 if (start < 0) {
13700 // Current activity is not in history stack; do nothing.
13701 return false;
13702 }
13703 int finishTo = start - 1;
13704 ActivityRecord parent = null;
13705 boolean foundParentInTask = false;
13706 if (dest != null) {
13707 TaskRecord tr = srec.task;
13708 for (int i = start - 1; i >= 0; i--) {
13709 ActivityRecord r = history.get(i);
13710 if (tr != r.task) {
13711 // Couldn't find parent in the same task; stop at the one above this.
13712 // (Root of current task; in-app "home" behavior)
13713 // Always at least finish the current activity.
13714 finishTo = Math.min(start - 1, i + 1);
13715 parent = history.get(finishTo);
13716 break;
13717 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13718 r.info.name.equals(dest.getClassName())) {
13719 finishTo = i;
13720 parent = r;
13721 foundParentInTask = true;
13722 break;
13723 }
13724 }
13725 }
13726
13727 if (mController != null) {
13728 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13729 if (next != null) {
13730 // ask watcher if this is allowed
13731 boolean resumeOK = true;
13732 try {
13733 resumeOK = mController.activityResuming(next.packageName);
13734 } catch (RemoteException e) {
13735 mController = null;
13736 }
13737
13738 if (!resumeOK) {
13739 return false;
13740 }
13741 }
13742 }
13743 final long origId = Binder.clearCallingIdentity();
13744 for (int i = start; i > finishTo; i--) {
13745 ActivityRecord r = history.get(i);
13746 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13747 "navigate-up");
13748 // Only return the supplied result for the first activity finished
13749 resultCode = Activity.RESULT_CANCELED;
13750 resultData = null;
13751 }
13752
13753 if (parent != null && foundParentInTask) {
13754 final int parentLaunchMode = parent.info.launchMode;
13755 final int destIntentFlags = destIntent.getFlags();
13756 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13757 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13758 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13759 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070013760 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070013761 } else {
13762 try {
13763 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13764 destIntent.getComponent(), 0, UserId.getCallingUserId());
13765 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13766 null, aInfo, parent.appToken, null,
13767 0, -1, parent.launchedFromUid, 0, null, true, null);
13768 foundParentInTask = res == ActivityManager.START_SUCCESS;
13769 } catch (RemoteException e) {
13770 foundParentInTask = false;
13771 }
13772 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13773 resultData, "navigate-up");
13774 }
13775 }
13776 Binder.restoreCallingIdentity(origId);
13777 return foundParentInTask;
13778 }
13779 }
13780
Dianne Hackborn5320eb82012-05-18 12:05:04 -070013781 public int getLaunchedFromUid(IBinder activityToken) {
13782 ActivityRecord srec = ActivityRecord.forToken(activityToken);
13783 if (srec == null) {
13784 return -1;
13785 }
13786 return srec.launchedFromUid;
13787 }
13788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013789 // =========================================================
13790 // LIFETIME MANAGEMENT
13791 // =========================================================
13792
Christopher Tatef46723b2012-01-26 14:19:24 -080013793 // Returns which broadcast queue the app is the current [or imminent] receiver
13794 // on, or 'null' if the app is not an active broadcast recipient.
13795 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13796 BroadcastRecord r = app.curReceiver;
13797 if (r != null) {
13798 return r.queue;
13799 }
13800
13801 // It's not the current receiver, but it might be starting up to become one
13802 synchronized (this) {
13803 for (BroadcastQueue queue : mBroadcastQueues) {
13804 r = queue.mPendingBroadcast;
13805 if (r != null && r.curApp == app) {
13806 // found it; report which queue it's in
13807 return queue;
13808 }
13809 }
13810 }
13811
13812 return null;
13813 }
13814
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013815 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013816 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013817 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013818 // This adjustment has already been computed. If we are calling
13819 // from the top, we may have already computed our adjustment with
13820 // an earlier hidden adjustment that isn't really for us... if
13821 // so, use the new hidden adjustment.
13822 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013823 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013824 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013825 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013826 }
13827
13828 if (app.thread == null) {
13829 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013830 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013831 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013832 }
13833
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013834 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13835 app.adjSource = null;
13836 app.adjTarget = null;
13837 app.empty = false;
13838 app.hidden = false;
13839
13840 final int activitiesSize = app.activities.size();
13841
Dianne Hackborn7d608422011-08-07 16:24:18 -070013842 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013843 // The max adjustment doesn't allow this app to be anything
13844 // below foreground, so it is not worth doing work for it.
13845 app.adjType = "fixed";
13846 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013847 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013848 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013849 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013850 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013851 // System process can do UI, and when they do we want to have
13852 // them trim their memory after the user leaves the UI. To
13853 // facilitate this, here we need to determine whether or not it
13854 // is currently showing UI.
13855 app.systemNoUi = true;
13856 if (app == TOP_APP) {
13857 app.systemNoUi = false;
13858 } else if (activitiesSize > 0) {
13859 for (int j = 0; j < activitiesSize; j++) {
13860 final ActivityRecord r = app.activities.get(j);
13861 if (r.visible) {
13862 app.systemNoUi = false;
13863 break;
13864 }
13865 }
13866 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013867 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013868 }
13869
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013870 app.keeping = false;
13871 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013872
The Android Open Source Project4df24232009-03-05 14:34:35 -080013873 // Determine the importance of the process, starting with most
13874 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013875 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013876 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013877 boolean foregroundActivities = false;
13878 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080013879 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013880 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013881 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013882 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013883 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013884 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013885 foregroundActivities = true;
13886 interesting = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013887 } else if (app.instrumentationClass != null) {
13888 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013889 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013890 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013891 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013892 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080013893 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013894 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013895 // counts as being in the foreground for OOM killer purposes.
13896 // It's placed in a sched group based on the nature of the
13897 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013898 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013899 schedGroup = (queue == mFgBroadcastQueue)
13900 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013901 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013902 } else if (app.executingServices.size() > 0) {
13903 // An app that is currently executing a service callback also
13904 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013905 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013906 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013907 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013908 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013909 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013910 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013911 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013912 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013913 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013914 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013915 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013916 // A very not-needed process. If this is lower in the lru list,
13917 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013918 adj = hiddenAdj;
13919 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013920 app.hidden = true;
13921 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013922 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013923 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013924
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013925 boolean hasStoppingActivities = false;
13926
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013927 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013928 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013929 for (int j = 0; j < activitiesSize; j++) {
13930 final ActivityRecord r = app.activities.get(j);
13931 if (r.visible) {
13932 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013933 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13934 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013935 app.adjType = "visible";
13936 }
13937 schedGroup = Process.THREAD_GROUP_DEFAULT;
13938 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013939 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013940 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013941 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013942 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13943 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013944 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013945 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013946 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013947 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013948 } else if (r.state == ActivityState.STOPPING) {
13949 // We will apply the actual adjustment later, because
13950 // we want to allow this process to immediately go through
13951 // any memory trimming that is in effect.
13952 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013953 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013954 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013955 }
13956 }
13957 }
13958
Dianne Hackborn7d608422011-08-07 16:24:18 -070013959 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013960 if (app.foregroundServices) {
13961 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013962 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013963 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013964 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013965 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013966 } else if (app.forcingToForeground != null) {
13967 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013968 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013969 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013970 app.adjType = "force-foreground";
13971 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013972 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013973 }
13974 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013975
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013976 if (app.foregroundServices) {
13977 interesting = true;
13978 }
13979
Dianne Hackborn7d608422011-08-07 16:24:18 -070013980 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013981 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013982 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013983 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013984 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013985 app.adjType = "heavy";
13986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013987
Dianne Hackborn7d608422011-08-07 16:24:18 -070013988 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013989 // This process is hosting what we currently consider to be the
13990 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013991 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013992 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013993 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013994 app.adjType = "home";
13995 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013996
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013997 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13998 && app.activities.size() > 0) {
13999 // This was the previous process that showed UI to the user.
14000 // We want to try to keep it around more aggressively, to give
14001 // a good experience around switching between two apps.
14002 adj = ProcessList.PREVIOUS_APP_ADJ;
14003 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
14004 app.hidden = false;
14005 app.adjType = "previous";
14006 }
14007
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014008 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
14009 + " reason=" + app.adjType);
14010
The Android Open Source Project4df24232009-03-05 14:34:35 -080014011 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014012 // there are applications dependent on our services or providers, but
14013 // this gives us a baseline and makes sure we don't get into an
14014 // infinite recursion.
14015 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014016 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014017
Christopher Tate6fa95972009-06-05 18:43:55 -070014018 if (mBackupTarget != null && app == mBackupTarget.app) {
14019 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070014020 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014021 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014022 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014023 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014024 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070014025 }
14026 }
14027
Dianne Hackborn7d608422011-08-07 16:24:18 -070014028 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014029 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014030 final long now = SystemClock.uptimeMillis();
14031 // This process is more important if the top activity is
14032 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070014033 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014034 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014035 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014036 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014037 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014038 // If this process has shown some UI, let it immediately
14039 // go to the LRU list because it may be pretty heavy with
14040 // UI stuff. We'll tag it with a label just to help
14041 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014042 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014043 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014044 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014045 } else {
14046 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
14047 // This service has seen some activity within
14048 // recent memory, so we will keep its process ahead
14049 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014050 if (adj > ProcessList.SERVICE_ADJ) {
14051 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014052 app.adjType = "started-services";
14053 app.hidden = false;
14054 }
14055 }
14056 // If we have let the service slide into the background
14057 // state, still have some text describing what it is doing
14058 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014059 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070014060 app.adjType = "started-bg-services";
14061 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014062 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014063 // Don't kill this process because it is doing work; it
14064 // has said it is doing work.
14065 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014066 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014067 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014068 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014069 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014070 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014071 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014072 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014073 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014074 // XXX should compute this based on the max of
14075 // all connected clients.
14076 ConnectionRecord cr = clist.get(i);
14077 if (cr.binding.client == app) {
14078 // Binding to ourself is not interesting.
14079 continue;
14080 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014081 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014082 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014083 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014084 int myHiddenAdj = hiddenAdj;
14085 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014086 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014087 myHiddenAdj = client.hiddenAdj;
14088 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014089 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014090 }
14091 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014092 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014093 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014094 String adjType = null;
14095 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
14096 // Not doing bind OOM management, so treat
14097 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014098 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014099 // If this process has shown some UI, let it immediately
14100 // go to the LRU list because it may be pretty heavy with
14101 // UI stuff. We'll tag it with a label just to help
14102 // debug and understand what is going on.
14103 if (adj > clientAdj) {
14104 adjType = "bound-bg-ui-services";
14105 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014106 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014107 clientAdj = adj;
14108 } else {
14109 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
14110 // This service has not seen activity within
14111 // recent memory, so allow it to drop to the
14112 // LRU list if there is no other reason to keep
14113 // it around. We'll also tag it with a label just
14114 // to help debug and undertand what is going on.
14115 if (adj > clientAdj) {
14116 adjType = "bound-bg-services";
14117 }
14118 clientAdj = adj;
14119 }
14120 }
14121 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014122 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014123 // If this process has recently shown UI, and
14124 // the process that is binding to it is less
14125 // important than being visible, then we don't
14126 // care about the binding as much as we care
14127 // about letting this process get into the LRU
14128 // list to be killed and restarted if needed for
14129 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014130 if (app.hasShownUi && app != mHomeProcess
14131 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014132 adjType = "bound-bg-ui-services";
14133 } else {
14134 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
14135 |Context.BIND_IMPORTANT)) != 0) {
14136 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014137 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
14138 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
14139 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14140 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14141 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014142 adj = clientAdj;
14143 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014144 app.pendingUiClean = true;
14145 if (adj > ProcessList.VISIBLE_APP_ADJ) {
14146 adj = ProcessList.VISIBLE_APP_ADJ;
14147 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014148 }
14149 if (!client.hidden) {
14150 app.hidden = false;
14151 }
14152 if (client.keeping) {
14153 app.keeping = true;
14154 }
14155 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014156 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014157 }
14158 if (adjType != null) {
14159 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014160 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14161 .REASON_SERVICE_IN_USE;
14162 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014163 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014164 app.adjTarget = s.name;
14165 }
14166 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14167 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14168 schedGroup = Process.THREAD_GROUP_DEFAULT;
14169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014170 }
14171 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014172 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
14173 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014174 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014175 (a.visible || a.state == ActivityState.RESUMED
14176 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014177 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014178 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14179 schedGroup = Process.THREAD_GROUP_DEFAULT;
14180 }
14181 app.hidden = false;
14182 app.adjType = "service";
14183 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14184 .REASON_SERVICE_IN_USE;
14185 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014186 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014187 app.adjTarget = s.name;
14188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014190 }
14191 }
14192 }
14193 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014194
Dianne Hackborn287952c2010-09-22 22:34:31 -070014195 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014196 // would like to avoid killing it unless it would prevent the current
14197 // application from running. By default we put the process in
14198 // with the rest of the background processes; as we scan through
14199 // its services we may bump it up from there.
14200 if (adj > hiddenAdj) {
14201 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014202 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014203 app.adjType = "bg-services";
14204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014205 }
14206
Dianne Hackborn7d608422011-08-07 16:24:18 -070014207 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014208 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014209 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014210 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014211 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014212 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014213 for (int i = cpr.connections.size()-1;
14214 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
14215 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
14216 i--) {
14217 ContentProviderConnection conn = cpr.connections.get(i);
14218 ProcessRecord client = conn.client;
14219 if (client == app) {
14220 // Being our own client is not interesting.
14221 continue;
14222 }
14223 int myHiddenAdj = hiddenAdj;
14224 if (myHiddenAdj > client.hiddenAdj) {
14225 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
14226 myHiddenAdj = client.hiddenAdj;
14227 } else {
14228 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070014229 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014230 }
14231 int clientAdj = computeOomAdjLocked(
14232 client, myHiddenAdj, TOP_APP, true, doingAll);
14233 if (adj > clientAdj) {
14234 if (app.hasShownUi && app != mHomeProcess
14235 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14236 app.adjType = "bg-ui-provider";
14237 } else {
14238 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
14239 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
14240 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014241 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014242 if (!client.hidden) {
14243 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014244 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014245 if (client.keeping) {
14246 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014247 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014248 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14249 .REASON_PROVIDER_IN_USE;
14250 app.adjSource = client;
14251 app.adjSourceOom = clientAdj;
14252 app.adjTarget = cpr.name;
14253 }
14254 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14255 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014256 }
14257 }
14258 // If the provider has external (non-framework) process
14259 // dependencies, ensure that its adjustment is at least
14260 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080014261 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014262 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
14263 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014264 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014265 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014266 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014267 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014268 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014269 }
14270 }
14271 }
14272 }
14273
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014274 if (adj == ProcessList.SERVICE_ADJ) {
14275 if (doingAll) {
14276 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
14277 mNewNumServiceProcs++;
14278 }
14279 if (app.serviceb) {
14280 adj = ProcessList.SERVICE_B_ADJ;
14281 }
14282 } else {
14283 app.serviceb = false;
14284 }
14285
14286 app.nonStoppingAdj = adj;
14287
14288 if (hasStoppingActivities) {
14289 // Only upgrade adjustment.
14290 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14291 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14292 app.adjType = "stopping";
14293 }
14294 }
14295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014296 app.curRawAdj = adj;
14297
Joe Onorato8a9b2202010-02-26 18:56:32 -080014298 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014299 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14300 if (adj > app.maxAdj) {
14301 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014302 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014303 schedGroup = Process.THREAD_GROUP_DEFAULT;
14304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014305 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014306 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014307 app.keeping = true;
14308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014309
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014310 if (app.hasAboveClient) {
14311 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14312 // then we need to drop its adjustment to be lower than the service's
14313 // in order to honor the request. We want to drop it by one adjustment
14314 // level... but there is special meaning applied to various levels so
14315 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014316 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014317 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014318 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14319 adj = ProcessList.VISIBLE_APP_ADJ;
14320 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14321 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14322 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14323 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014324 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014325 adj++;
14326 }
14327 }
14328
Dianne Hackborna93c2c12012-05-31 15:29:36 -070014329 int importance = app.memImportance;
14330 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
14331 app.curAdj = adj;
14332 app.curSchedGroup = schedGroup;
14333 if (!interesting) {
14334 // For this reporting, if there is not something explicitly
14335 // interesting in this process then we will push it to the
14336 // background importance.
14337 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
14338 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
14339 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
14340 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
14341 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
14342 } else if (adj >= ProcessList.HOME_APP_ADJ) {
14343 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
14344 } else if (adj >= ProcessList.SERVICE_ADJ) {
14345 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
14346 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
14347 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
14348 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
14349 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
14350 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
14351 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
14352 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
14353 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
14354 } else {
14355 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
14356 }
14357 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014358
Dianne Hackborna93c2c12012-05-31 15:29:36 -070014359 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
14360 if (foregroundActivities != app.foregroundActivities) {
14361 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
14362 }
14363 if (changes != 0) {
14364 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
14365 app.memImportance = importance;
14366 app.foregroundActivities = foregroundActivities;
14367 int i = mPendingProcessChanges.size()-1;
14368 ProcessChangeItem item = null;
14369 while (i >= 0) {
14370 item = mPendingProcessChanges.get(i);
14371 if (item.pid == app.pid) {
14372 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
14373 break;
14374 }
14375 i--;
14376 }
14377 if (i < 0) {
14378 // No existing item in pending changes; need a new one.
14379 final int NA = mAvailProcessChanges.size();
14380 if (NA > 0) {
14381 item = mAvailProcessChanges.remove(NA-1);
14382 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
14383 } else {
14384 item = new ProcessChangeItem();
14385 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
14386 }
14387 item.changes = 0;
14388 item.pid = app.pid;
14389 item.uid = app.info.uid;
14390 if (mPendingProcessChanges.size() == 0) {
14391 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
14392 "*** Enqueueing dispatch processes changed!");
14393 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
14394 }
14395 mPendingProcessChanges.add(item);
14396 }
14397 item.changes |= changes;
14398 item.importance = importance;
14399 item.foregroundActivities = foregroundActivities;
14400 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
14401 + Integer.toHexString(System.identityHashCode(item))
14402 + " " + app.toShortString() + ": changes=" + item.changes
14403 + " importance=" + item.importance
14404 + " foreground=" + item.foregroundActivities
14405 + " type=" + app.adjType + " source=" + app.adjSource
14406 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014407 }
14408
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014409 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014410 }
14411
14412 /**
14413 * Ask a given process to GC right now.
14414 */
14415 final void performAppGcLocked(ProcessRecord app) {
14416 try {
14417 app.lastRequestedGc = SystemClock.uptimeMillis();
14418 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014419 if (app.reportLowMemory) {
14420 app.reportLowMemory = false;
14421 app.thread.scheduleLowMemory();
14422 } else {
14423 app.thread.processInBackground();
14424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014425 }
14426 } catch (Exception e) {
14427 // whatever.
14428 }
14429 }
14430
14431 /**
14432 * Returns true if things are idle enough to perform GCs.
14433 */
Josh Bartel7f208742010-02-25 11:01:44 -060014434 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014435 boolean processingBroadcasts = false;
14436 for (BroadcastQueue q : mBroadcastQueues) {
14437 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14438 processingBroadcasts = true;
14439 }
14440 }
14441 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014442 && (mSleeping || (mMainStack.mResumedActivity != null &&
14443 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014444 }
14445
14446 /**
14447 * Perform GCs on all processes that are waiting for it, but only
14448 * if things are idle.
14449 */
14450 final void performAppGcsLocked() {
14451 final int N = mProcessesToGc.size();
14452 if (N <= 0) {
14453 return;
14454 }
Josh Bartel7f208742010-02-25 11:01:44 -060014455 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014456 while (mProcessesToGc.size() > 0) {
14457 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014458 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014459 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14460 <= SystemClock.uptimeMillis()) {
14461 // To avoid spamming the system, we will GC processes one
14462 // at a time, waiting a few seconds between each.
14463 performAppGcLocked(proc);
14464 scheduleAppGcsLocked();
14465 return;
14466 } else {
14467 // It hasn't been long enough since we last GCed this
14468 // process... put it in the list to wait for its time.
14469 addProcessToGcListLocked(proc);
14470 break;
14471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014472 }
14473 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014474
14475 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014476 }
14477 }
14478
14479 /**
14480 * If all looks good, perform GCs on all processes waiting for them.
14481 */
14482 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014483 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014484 performAppGcsLocked();
14485 return;
14486 }
14487 // Still not idle, wait some more.
14488 scheduleAppGcsLocked();
14489 }
14490
14491 /**
14492 * Schedule the execution of all pending app GCs.
14493 */
14494 final void scheduleAppGcsLocked() {
14495 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014496
14497 if (mProcessesToGc.size() > 0) {
14498 // Schedule a GC for the time to the next process.
14499 ProcessRecord proc = mProcessesToGc.get(0);
14500 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14501
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014502 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014503 long now = SystemClock.uptimeMillis();
14504 if (when < (now+GC_TIMEOUT)) {
14505 when = now + GC_TIMEOUT;
14506 }
14507 mHandler.sendMessageAtTime(msg, when);
14508 }
14509 }
14510
14511 /**
14512 * Add a process to the array of processes waiting to be GCed. Keeps the
14513 * list in sorted order by the last GC time. The process can't already be
14514 * on the list.
14515 */
14516 final void addProcessToGcListLocked(ProcessRecord proc) {
14517 boolean added = false;
14518 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14519 if (mProcessesToGc.get(i).lastRequestedGc <
14520 proc.lastRequestedGc) {
14521 added = true;
14522 mProcessesToGc.add(i+1, proc);
14523 break;
14524 }
14525 }
14526 if (!added) {
14527 mProcessesToGc.add(0, proc);
14528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014529 }
14530
14531 /**
14532 * Set up to ask a process to GC itself. This will either do it
14533 * immediately, or put it on the list of processes to gc the next
14534 * time things are idle.
14535 */
14536 final void scheduleAppGcLocked(ProcessRecord app) {
14537 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014538 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014539 return;
14540 }
14541 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014542 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014543 scheduleAppGcsLocked();
14544 }
14545 }
14546
Dianne Hackborn287952c2010-09-22 22:34:31 -070014547 final void checkExcessivePowerUsageLocked(boolean doKills) {
14548 updateCpuStatsNow();
14549
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014550 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014551 boolean doWakeKills = doKills;
14552 boolean doCpuKills = doKills;
14553 if (mLastPowerCheckRealtime == 0) {
14554 doWakeKills = false;
14555 }
14556 if (mLastPowerCheckUptime == 0) {
14557 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014558 }
14559 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014560 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014561 }
14562 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014563 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14564 final long curUptime = SystemClock.uptimeMillis();
14565 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14566 mLastPowerCheckRealtime = curRealtime;
14567 mLastPowerCheckUptime = curUptime;
14568 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14569 doWakeKills = false;
14570 }
14571 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14572 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014573 }
14574 int i = mLruProcesses.size();
14575 while (i > 0) {
14576 i--;
14577 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014578 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014579 long wtime;
14580 synchronized (stats) {
14581 wtime = stats.getProcessWakeTime(app.info.uid,
14582 app.pid, curRealtime);
14583 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014584 long wtimeUsed = wtime - app.lastWakeTime;
14585 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14586 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014587 StringBuilder sb = new StringBuilder(128);
14588 sb.append("Wake for ");
14589 app.toShortString(sb);
14590 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014591 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014592 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014593 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014594 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014595 sb.append((wtimeUsed*100)/realtimeSince);
14596 sb.append("%)");
14597 Slog.i(TAG, sb.toString());
14598 sb.setLength(0);
14599 sb.append("CPU for ");
14600 app.toShortString(sb);
14601 sb.append(": over ");
14602 TimeUtils.formatDuration(uptimeSince, sb);
14603 sb.append(" used ");
14604 TimeUtils.formatDuration(cputimeUsed, sb);
14605 sb.append(" (");
14606 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014607 sb.append("%)");
14608 Slog.i(TAG, sb.toString());
14609 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014610 // If a process has held a wake lock for more
14611 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014612 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014613 if (doWakeKills && realtimeSince > 0
14614 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14615 synchronized (stats) {
14616 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14617 realtimeSince, wtimeUsed);
14618 }
14619 Slog.w(TAG, "Excessive wake lock in " + app.processName
14620 + " (pid " + app.pid + "): held " + wtimeUsed
14621 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014622 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14623 app.processName, app.setAdj, "excessive wake lock");
14624 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014625 } else if (doCpuKills && uptimeSince > 0
14626 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14627 synchronized (stats) {
14628 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14629 uptimeSince, cputimeUsed);
14630 }
14631 Slog.w(TAG, "Excessive CPU in " + app.processName
14632 + " (pid " + app.pid + "): used " + cputimeUsed
14633 + " during " + uptimeSince);
14634 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14635 app.processName, app.setAdj, "excessive cpu");
14636 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014637 } else {
14638 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014639 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014640 }
14641 }
14642 }
14643 }
14644
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014645 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014646 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014647 app.hiddenAdj = hiddenAdj;
14648
14649 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014650 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014651 }
14652
Dianne Hackborn287952c2010-09-22 22:34:31 -070014653 final boolean wasKeeping = app.keeping;
14654
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014655 boolean success = true;
14656
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014657 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014658
Jeff Brown10e89712011-07-08 18:52:57 -070014659 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070014660 if (wasKeeping && !app.keeping) {
14661 // This app is no longer something we want to keep. Note
14662 // its current wake lock time to later know to kill it if
14663 // it is not behaving well.
14664 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14665 synchronized (stats) {
14666 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14667 app.pid, SystemClock.elapsedRealtime());
14668 }
14669 app.lastCpuTime = app.curCpuTime;
14670 }
14671
14672 app.setRawAdj = app.curRawAdj;
14673 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014674
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014675 if (app.curAdj != app.setAdj) {
14676 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014677 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014678 TAG, "Set " + app.pid + " " + app.processName +
14679 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014680 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014681 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014682 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014683 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014684 }
14685 }
14686 if (app.setSchedGroup != app.curSchedGroup) {
14687 app.setSchedGroup = app.curSchedGroup;
14688 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14689 "Setting process group of " + app.processName
14690 + " to " + app.curSchedGroup);
14691 if (app.waitingToKill != null &&
14692 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14693 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14694 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14695 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070014696 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070014697 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014698 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014699 } else {
14700 if (true) {
14701 long oldId = Binder.clearCallingIdentity();
14702 try {
14703 Process.setProcessGroup(app.pid, app.curSchedGroup);
14704 } catch (Exception e) {
14705 Slog.w(TAG, "Failed setting process group of " + app.pid
14706 + " to " + app.curSchedGroup);
14707 e.printStackTrace();
14708 } finally {
14709 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014710 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014711 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014712 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014713 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014714 app.thread.setSchedulingGroup(app.curSchedGroup);
14715 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014716 }
14717 }
14718 }
14719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014720 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014721 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014722 }
14723
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014724 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014725 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014726 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014727 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014728 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014729 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014730 }
14731 }
14732 return resumedActivity;
14733 }
14734
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014735 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014736 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014737 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14738 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014739 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14740 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014741
14742 mAdjSeq++;
14743
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014744 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014745 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14746 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014747 if (nowHidden != wasHidden) {
14748 // Changed to/from hidden state, so apps after it in the LRU
14749 // list may also be changed.
14750 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014751 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014752 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014753 }
14754
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014755 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014756 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014757 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14758
14759 if (false) {
14760 RuntimeException e = new RuntimeException();
14761 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014762 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014763 }
14764
14765 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014766 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014767
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014768 // Let's determine how many processes we have running vs.
14769 // how many slots we have for background processes; we may want
14770 // to put multiple processes in a slot of there are enough of
14771 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014772 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014773 int factor = (mLruProcesses.size()-4)/numSlots;
14774 if (factor < 1) factor = 1;
14775 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014776 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014777 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014778
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014779 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014780 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014781 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014782 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014783 while (i > 0) {
14784 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014785 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014786 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014787 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14788 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014789 && app.curAdj == curHiddenAdj) {
14790 step++;
14791 if (step >= factor) {
14792 step = 0;
14793 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014794 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014795 }
14796 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014797 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014798 numHidden++;
14799 if (numHidden > mProcessLimit) {
14800 Slog.i(TAG, "No longer want " + app.processName
14801 + " (pid " + app.pid + "): hidden #" + numHidden);
14802 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14803 app.processName, app.setAdj, "too many background");
14804 app.killedBackground = true;
14805 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014806 }
14807 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014808 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14809 // If this is an isolated process, and there are no
14810 // services running in it, then the process is no longer
14811 // needed. We agressively kill these because we can by
14812 // definition not re-use the same process again, and it is
14813 // good to avoid having whatever code was running in them
14814 // left sitting around after no longer needed.
14815 Slog.i(TAG, "Isolated process " + app.processName
14816 + " (pid " + app.pid + ") no longer needed");
14817 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14818 app.processName, app.setAdj, "isolated not needed");
14819 app.killedBackground = true;
14820 Process.killProcessQuiet(app.pid);
14821 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014822 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14823 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14824 && !app.killedBackground) {
14825 numTrimming++;
14826 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014827 }
14828 }
14829
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014830 mNumServiceProcs = mNewNumServiceProcs;
14831
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014832 // Now determine the memory trimming level of background processes.
14833 // Unfortunately we need to start at the back of the list to do this
14834 // properly. We only do this if the number of background apps we
14835 // are managing to keep around is less than half the maximum we desire;
14836 // if we are keeping a good number around, we'll let them use whatever
14837 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014838 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014839 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014840 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014841 int minFactor = 2;
14842 if (mHomeProcess != null) minFactor++;
14843 if (mPreviousProcess != null) minFactor++;
14844 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014845 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014846 int fgTrimLevel;
14847 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14848 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14849 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14850 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14851 } else {
14852 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14853 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014854 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014855 for (i=0; i<N; i++) {
14856 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014857 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14858 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014859 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014860 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14861 try {
14862 app.thread.scheduleTrimMemory(curLevel);
14863 } catch (RemoteException e) {
14864 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014865 if (false) {
14866 // For now we won't do this; our memory trimming seems
14867 // to be good enough at this point that destroying
14868 // activities causes more harm than good.
14869 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14870 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014871 // Need to do this on its own message because the stack may not
14872 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014873 // For these apps we will also finish their activities
14874 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014875 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014876 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014877 }
14878 }
14879 app.trimMemoryLevel = curLevel;
14880 step++;
14881 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014882 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014883 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014884 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14885 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014886 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014887 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14888 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014889 break;
14890 }
14891 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014892 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014893 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014894 && app.thread != null) {
14895 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014896 app.thread.scheduleTrimMemory(
14897 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014898 } catch (RemoteException e) {
14899 }
14900 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014901 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014902 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014903 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014904 && app.pendingUiClean) {
14905 // If this application is now in the background and it
14906 // had done UI, then give it the special trim level to
14907 // have it free UI resources.
14908 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14909 if (app.trimMemoryLevel < level && app.thread != null) {
14910 try {
14911 app.thread.scheduleTrimMemory(level);
14912 } catch (RemoteException e) {
14913 }
14914 }
14915 app.pendingUiClean = false;
14916 }
14917 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014918 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014919 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014920 } catch (RemoteException e) {
14921 }
14922 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014923 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014924 }
14925 }
14926 } else {
14927 final int N = mLruProcesses.size();
14928 for (i=0; i<N; i++) {
14929 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014930 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014931 && app.pendingUiClean) {
14932 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14933 && app.thread != null) {
14934 try {
14935 app.thread.scheduleTrimMemory(
14936 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14937 } catch (RemoteException e) {
14938 }
14939 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014940 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014941 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014942 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014943 }
14944 }
14945
14946 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014947 // Need to do this on its own message because the stack may not
14948 // be in a consistent state at this point.
14949 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014951 }
14952
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014953 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014954 synchronized (this) {
14955 int i;
14956
14957 // First remove any unused application processes whose package
14958 // has been removed.
14959 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14960 final ProcessRecord app = mRemovedProcesses.get(i);
14961 if (app.activities.size() == 0
14962 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014963 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014964 TAG, "Exiting empty application process "
14965 + app.processName + " ("
14966 + (app.thread != null ? app.thread.asBinder() : null)
14967 + ")\n");
14968 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014969 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14970 app.processName, app.setAdj, "empty");
14971 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014972 } else {
14973 try {
14974 app.thread.scheduleExit();
14975 } catch (Exception e) {
14976 // Ignore exceptions.
14977 }
14978 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014979 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014980 mRemovedProcesses.remove(i);
14981
14982 if (app.persistent) {
14983 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014984 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014985 }
14986 }
14987 }
14988 }
14989
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014990 // Now update the oom adj for all processes.
14991 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014992 }
14993 }
14994
14995 /** This method sends the specified signal to each of the persistent apps */
14996 public void signalPersistentProcesses(int sig) throws RemoteException {
14997 if (sig != Process.SIGNAL_USR1) {
14998 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14999 }
15000
15001 synchronized (this) {
15002 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
15003 != PackageManager.PERMISSION_GRANTED) {
15004 throw new SecurityException("Requires permission "
15005 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
15006 }
15007
Dianne Hackborndd71fc82009-12-16 19:24:32 -080015008 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
15009 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015010 if (r.thread != null && r.persistent) {
15011 Process.sendSignal(r.pid, sig);
15012 }
15013 }
15014 }
15015 }
15016
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015017 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
15018 if (proc == null || proc == mProfileProc) {
15019 proc = mProfileProc;
15020 path = mProfileFile;
15021 profileType = mProfileType;
15022 clearProfilerLocked();
15023 }
15024 if (proc == null) {
15025 return;
15026 }
15027 try {
15028 proc.thread.profilerControl(false, path, null, profileType);
15029 } catch (RemoteException e) {
15030 throw new IllegalStateException("Process disappeared");
15031 }
15032 }
15033
15034 private void clearProfilerLocked() {
15035 if (mProfileFd != null) {
15036 try {
15037 mProfileFd.close();
15038 } catch (IOException e) {
15039 }
15040 }
15041 mProfileApp = null;
15042 mProfileProc = null;
15043 mProfileFile = null;
15044 mProfileType = 0;
15045 mAutoStopProfiler = false;
15046 }
15047
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015048 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070015049 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015050
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015051 try {
15052 synchronized (this) {
15053 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
15054 // its own permission.
15055 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
15056 != PackageManager.PERMISSION_GRANTED) {
15057 throw new SecurityException("Requires permission "
15058 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015059 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015060
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015061 if (start && fd == null) {
15062 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015063 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015064
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015065 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015066 if (process != null) {
15067 try {
15068 int pid = Integer.parseInt(process);
15069 synchronized (mPidsSelfLocked) {
15070 proc = mPidsSelfLocked.get(pid);
15071 }
15072 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015073 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015074
15075 if (proc == null) {
15076 HashMap<String, SparseArray<ProcessRecord>> all
15077 = mProcessNames.getMap();
15078 SparseArray<ProcessRecord> procs = all.get(process);
15079 if (procs != null && procs.size() > 0) {
15080 proc = procs.valueAt(0);
15081 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015082 }
15083 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015084
15085 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015086 throw new IllegalArgumentException("Unknown process: " + process);
15087 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015088
15089 if (start) {
15090 stopProfilerLocked(null, null, 0);
15091 setProfileApp(proc.info, proc.processName, path, fd, false);
15092 mProfileProc = proc;
15093 mProfileType = profileType;
15094 try {
15095 fd = fd.dup();
15096 } catch (IOException e) {
15097 fd = null;
15098 }
15099 proc.thread.profilerControl(start, path, fd, profileType);
15100 fd = null;
15101 mProfileFd = null;
15102 } else {
15103 stopProfilerLocked(proc, path, profileType);
15104 if (fd != null) {
15105 try {
15106 fd.close();
15107 } catch (IOException e) {
15108 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015109 }
15110 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015111
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015112 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015113 }
15114 } catch (RemoteException e) {
15115 throw new IllegalStateException("Process disappeared");
15116 } finally {
15117 if (fd != null) {
15118 try {
15119 fd.close();
15120 } catch (IOException e) {
15121 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015122 }
15123 }
15124 }
Andy McFadden824c5102010-07-09 16:26:57 -070015125
15126 public boolean dumpHeap(String process, boolean managed,
15127 String path, ParcelFileDescriptor fd) throws RemoteException {
15128
15129 try {
15130 synchronized (this) {
15131 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
15132 // its own permission (same as profileControl).
15133 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
15134 != PackageManager.PERMISSION_GRANTED) {
15135 throw new SecurityException("Requires permission "
15136 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
15137 }
15138
15139 if (fd == null) {
15140 throw new IllegalArgumentException("null fd");
15141 }
15142
15143 ProcessRecord proc = null;
15144 try {
15145 int pid = Integer.parseInt(process);
15146 synchronized (mPidsSelfLocked) {
15147 proc = mPidsSelfLocked.get(pid);
15148 }
15149 } catch (NumberFormatException e) {
15150 }
15151
15152 if (proc == null) {
15153 HashMap<String, SparseArray<ProcessRecord>> all
15154 = mProcessNames.getMap();
15155 SparseArray<ProcessRecord> procs = all.get(process);
15156 if (procs != null && procs.size() > 0) {
15157 proc = procs.valueAt(0);
15158 }
15159 }
15160
15161 if (proc == null || proc.thread == null) {
15162 throw new IllegalArgumentException("Unknown process: " + process);
15163 }
15164
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080015165 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
15166 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070015167 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
15168 throw new SecurityException("Process not debuggable: " + proc);
15169 }
15170 }
15171
15172 proc.thread.dumpHeap(managed, path, fd);
15173 fd = null;
15174 return true;
15175 }
15176 } catch (RemoteException e) {
15177 throw new IllegalStateException("Process disappeared");
15178 } finally {
15179 if (fd != null) {
15180 try {
15181 fd.close();
15182 } catch (IOException e) {
15183 }
15184 }
15185 }
15186 }
15187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015188 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
15189 public void monitor() {
15190 synchronized (this) { }
15191 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080015192
Dianne Hackborna573f6a2012-02-09 16:12:18 -080015193 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080015194 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
15195 ProcessRecord processRecord = mLruProcesses.get(i);
15196 try {
15197 if (processRecord.thread != null) {
15198 processRecord.thread.setCoreSettings(settings);
15199 }
15200 } catch (RemoteException re) {
15201 /* ignore */
15202 }
15203 }
15204 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015205
15206 // Multi-user methods
15207
Amith Yamasani742a6712011-05-04 14:49:28 -070015208 private int mCurrentUserId;
15209 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
15210
15211 public boolean switchUser(int userId) {
15212 final int callingUid = Binder.getCallingUid();
15213 if (callingUid != 0 && callingUid != Process.myUid()) {
15214 Slog.e(TAG, "Trying to switch user from unauthorized app");
15215 return false;
15216 }
15217 if (mCurrentUserId == userId)
15218 return true;
15219
15220 synchronized (this) {
15221 // Check if user is already logged in, otherwise check if user exists first before
15222 // adding to the list of logged in users.
15223 if (mLoggedInUsers.indexOfKey(userId) < 0) {
15224 if (!userExists(userId)) {
15225 return false;
15226 }
15227 mLoggedInUsers.append(userId, userId);
15228 }
15229
15230 mCurrentUserId = userId;
15231 boolean haveActivities = mMainStack.switchUser(userId);
15232 if (!haveActivities) {
15233 startHomeActivityLocked(userId);
15234 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080015235
Amith Yamasani37ce3a82012-02-06 12:04:42 -080015236 }
Amith Yamasani13593602012-03-22 16:16:17 -070015237
15238 // Inform of user switch
15239 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
15240 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
15241 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
15242
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015243 return true;
15244 }
Amith Yamasani742a6712011-05-04 14:49:28 -070015245
Amith Yamasani52f1d752012-03-28 18:19:29 -070015246 @Override
15247 public UserInfo getCurrentUser() throws RemoteException {
15248 final int callingUid = Binder.getCallingUid();
15249 if (callingUid != 0 && callingUid != Process.myUid()) {
15250 Slog.e(TAG, "Trying to get user from unauthorized app");
15251 return null;
15252 }
15253 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
15254 }
15255
Amith Yamasani13593602012-03-22 16:16:17 -070015256 private void onUserRemoved(Intent intent) {
15257 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
15258 if (extraUserId < 1) return;
15259
15260 // Kill all the processes for the user
15261 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
15262 synchronized (this) {
15263 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
15264 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
15265 SparseArray<ProcessRecord> uids = uidMap.getValue();
15266 for (int i = 0; i < uids.size(); i++) {
15267 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
15268 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
15269 }
15270 }
15271 }
15272
15273 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
15274 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
15275 false, false, true, true, extraUserId);
15276 }
15277 }
15278 }
15279
Amith Yamasani742a6712011-05-04 14:49:28 -070015280 private boolean userExists(int userId) {
15281 try {
Amith Yamasani13593602012-03-22 16:16:17 -070015282 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
15283 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070015284 } catch (RemoteException re) {
15285 // Won't happen, in same process
15286 }
15287
15288 return false;
15289 }
15290
Amith Yamasani37ce3a82012-02-06 12:04:42 -080015291 private void checkValidCaller(int uid, int userId) {
15292 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
15293
15294 throw new SecurityException("Caller uid=" + uid
15295 + " is not privileged to communicate with user=" + userId);
15296 }
Amith Yamasani742a6712011-05-04 14:49:28 -070015297
15298 private int applyUserId(int uid, int userId) {
15299 return UserId.getUid(userId, uid);
15300 }
15301
15302 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080015303 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070015304 ApplicationInfo newInfo = new ApplicationInfo(info);
15305 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070015306 newInfo.dataDir = USER_DATA_DIR + userId + "/"
15307 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070015308 return newInfo;
15309 }
15310
15311 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070015312 if (aInfo == null
15313 || (userId < 1 && aInfo.applicationInfo.uid < UserId.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070015314 return aInfo;
15315 }
15316
15317 ActivityInfo info = new ActivityInfo(aInfo);
15318 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
15319 return info;
15320 }
15321
15322 static class ServiceMap {
15323
15324 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
15325 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
15326 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
15327 mServicesByIntentPerUser = new SparseArray<
15328 HashMap<Intent.FilterComparison, ServiceRecord>>();
15329
15330 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
15331 // TODO: Deal with global services
15332 if (DEBUG_MU)
15333 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
15334 return getServices(callingUser).get(name);
15335 }
15336
15337 ServiceRecord getServiceByName(ComponentName name) {
15338 return getServiceByName(name, -1);
15339 }
15340
15341 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15342 // TODO: Deal with global services
15343 if (DEBUG_MU)
15344 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
15345 return getServicesByIntent(callingUser).get(filter);
15346 }
15347
15348 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
15349 return getServiceByIntent(filter, -1);
15350 }
15351
15352 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
15353 // TODO: Deal with global services
15354 getServices(callingUser).put(name, value);
15355 }
15356
15357 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
15358 ServiceRecord value) {
15359 // TODO: Deal with global services
15360 getServicesByIntent(callingUser).put(filter, value);
15361 }
15362
15363 void removeServiceByName(ComponentName name, int callingUser) {
15364 // TODO: Deal with global services
15365 ServiceRecord removed = getServices(callingUser).remove(name);
15366 if (DEBUG_MU)
15367 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
15368 + " removed=" + removed);
15369 }
15370
15371 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15372 // TODO: Deal with global services
15373 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15374 if (DEBUG_MU)
15375 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15376 + " removed=" + removed);
15377 }
15378
15379 Collection<ServiceRecord> getAllServices(int callingUser) {
15380 // TODO: Deal with global services
15381 return getServices(callingUser).values();
15382 }
15383
15384 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15385 HashMap map = mServicesByNamePerUser.get(callingUser);
15386 if (map == null) {
15387 map = new HashMap<ComponentName, ServiceRecord>();
15388 mServicesByNamePerUser.put(callingUser, map);
15389 }
15390 return map;
15391 }
15392
15393 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15394 int callingUser) {
15395 HashMap map = mServicesByIntentPerUser.get(callingUser);
15396 if (map == null) {
15397 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15398 mServicesByIntentPerUser.put(callingUser, map);
15399 }
15400 return map;
15401 }
15402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015403}