blob: 8245d671ba87a4b324e92d33739d212167631727 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackborn860755f2010-06-03 18:47:52 -070021import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070023import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070024import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.IntentResolver;
26import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.SystemServer;
28import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080030import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031
Dianne Hackborndd71fc82009-12-16 19:24:32 -080032import dalvik.system.Zygote;
33
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.app.Activity;
35import android.app.ActivityManager;
36import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070037import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.app.ActivityThread;
39import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070040import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020041import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070043import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.app.IApplicationThread;
45import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070046import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070047import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.app.IServiceConnection;
49import android.app.IThumbnailReceiver;
50import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070051import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070052import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.app.PendingIntent;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070054import android.app.Service;
Christopher Tate45281862010-03-05 15:46:30 -080055import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020056import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080057import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080058import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070059import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070061import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.ContentResolver;
63import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020064import android.content.DialogInterface;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070065import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070066import android.content.IIntentReceiver;
67import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070068import android.content.Intent;
69import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070070import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.content.pm.ActivityInfo;
72import android.content.pm.ApplicationInfo;
73import android.content.pm.ConfigurationInfo;
74import android.content.pm.IPackageDataObserver;
75import android.content.pm.IPackageManager;
76import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080077import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.content.pm.PackageManager;
Adam Powelldd8fab22012-03-22 17:47:27 -070079import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070080import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.content.pm.ProviderInfo;
82import android.content.pm.ResolveInfo;
83import android.content.pm.ServiceInfo;
Amith Yamasani742a6712011-05-04 14:49:28 -070084import android.content.pm.UserInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040085import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.content.res.Configuration;
87import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070088import android.net.Proxy;
89import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.net.Uri;
91import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080092import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080093import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070094import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080095import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080097import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.FileUtils;
99import android.os.Handler;
100import android.os.IBinder;
101import android.os.IPermissionController;
102import android.os.Looper;
103import android.os.Message;
104import android.os.Parcel;
105import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700107import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.os.RemoteException;
109import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700110import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import android.os.SystemClock;
112import android.os.SystemProperties;
Amith Yamasani742a6712011-05-04 14:49:28 -0700113import android.os.UserId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700115import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800117import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700118import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700120import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700122import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700123import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import android.view.Gravity;
125import android.view.LayoutInflater;
126import android.view.View;
127import android.view.WindowManager;
128import android.view.WindowManagerPolicy;
129
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700130import java.io.BufferedInputStream;
131import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700132import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700133import java.io.DataInputStream;
134import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.File;
136import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700137import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700139import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200140import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800141import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700143import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.lang.ref.WeakReference;
145import java.util.ArrayList;
Amith Yamasani742a6712011-05-04 14:49:28 -0700146import java.util.Collection;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700147import java.util.Collections;
148import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149import java.util.HashMap;
150import java.util.HashSet;
151import java.util.Iterator;
152import java.util.List;
153import java.util.Locale;
154import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700155import java.util.Map.Entry;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700156import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700157import java.util.concurrent.atomic.AtomicBoolean;
158import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700160public final class ActivityManagerService extends ActivityManagerNative
161 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700162 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700164 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400166 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 static final boolean DEBUG_SWITCH = localLOGV || false;
168 static final boolean DEBUG_TASKS = localLOGV || false;
169 static final boolean DEBUG_PAUSE = localLOGV || false;
170 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
171 static final boolean DEBUG_TRANSITION = localLOGV || false;
172 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800173 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700174 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700176 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 static final boolean DEBUG_VISBILITY = localLOGV || false;
178 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700179 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700180 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800181 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700183 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700184 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700185 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700186 static final boolean DEBUG_POWER = localLOGV || false;
187 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700188 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189 static final boolean VALIDATE_TOKENS = false;
190 static final boolean SHOW_ACTIVITY_START_TIME = true;
191
192 // Control over CPU and battery monitoring.
193 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
194 static final boolean MONITOR_CPU_USAGE = true;
195 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
196 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
197 static final boolean MONITOR_THREAD_CPU_USAGE = false;
198
Dianne Hackborn1655be42009-05-08 14:29:01 -0700199 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700200 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700201
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800202 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700204 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 // Maximum number of recent tasks that we can remember.
207 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700208
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700209 // Amount of time after a call to stopAppSwitches() during which we will
210 // prevent further untrusted switches from happening.
211 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
213 // How long we wait for a launched process to attach to the activity manager
214 // before we decide it's never going to come up for real.
215 static final int PROC_START_TIMEOUT = 10*1000;
216
Jeff Brown3f9dd282011-07-08 20:02:19 -0700217 // How long we wait for a launched process to attach to the activity manager
218 // before we decide it's never going to come up for real, when the process was
219 // started with a wrapper for instrumentation (such as Valgrind) because it
220 // could take much longer than usual.
221 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 // How long to wait after going idle before forcing apps to GC.
224 static final int GC_TIMEOUT = 5*1000;
225
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700226 // The minimum amount of time between successive GC requests for a process.
227 static final int GC_MIN_INTERVAL = 60*1000;
228
Dianne Hackborn287952c2010-09-22 22:34:31 -0700229 // The rate at which we check for apps using excessive power -- 15 mins.
230 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
231
232 // The minimum sample duration we will allow before deciding we have
233 // enough data on wake locks to start killing things.
234 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
235
236 // The minimum sample duration we will allow before deciding we have
237 // enough data on CPU usage to start killing things.
238 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800241 static final int BROADCAST_FG_TIMEOUT = 10*1000;
242 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
244 // How long we wait for a service to finish executing.
245 static final int SERVICE_TIMEOUT = 20*1000;
246
247 // How long a service needs to be running until restarting its process
248 // is no longer considered to be a relaunch of the service.
249 static final int SERVICE_RESTART_DURATION = 5*1000;
250
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700251 // How long a service needs to be running until it will start back at
252 // SERVICE_RESTART_DURATION after being killed.
253 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
254
255 // Multiplying factor to increase restart duration time by, for each time
256 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
257 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
258
259 // The minimum amount of time between restarting services that we allow.
260 // That is, when multiple services are restarting, we won't allow each
261 // to restart less than this amount of time from the last one.
262 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 // Maximum amount of time for there to be no activity on a service before
265 // we consider it non-essential and allow its process to go on the
266 // LRU background list.
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700267 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268
269 // How long we wait until we timeout on key dispatching.
270 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 // How long we wait until we timeout on key dispatching during instrumentation.
273 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
274
Dan Egnor42471dd2010-01-07 17:25:22 -0800275 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276
277 static final String[] EMPTY_STRING_ARRAY = new String[0];
278
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700279 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700280
281 private final boolean mHeadless;
282
Joe Onorato54a4a412011-11-02 20:50:08 -0700283 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
284 // default actuion automatically. Important for devices without direct input
285 // devices.
286 private boolean mShowDialogs = true;
287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700289 * Description of a request to start a new activity, which has been held
290 * due to app switches being disabled.
291 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700292 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700293 ActivityRecord r;
294 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700295 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700296 }
297
298 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
299 = new ArrayList<PendingActivityLaunch>();
300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800302 BroadcastQueue mFgBroadcastQueue;
303 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800304 // Convenient for easy iteration over the queues. Foreground is first
305 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800306 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800307
308 BroadcastQueue broadcastQueueForIntent(Intent intent) {
309 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
310 if (DEBUG_BACKGROUND_BROADCAST) {
311 Slog.i(TAG, "Broadcast intent " + intent + " on "
312 + (isFg ? "foreground" : "background")
313 + " queue");
314 }
315 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
316 }
317
318 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
319 for (BroadcastQueue queue : mBroadcastQueues) {
320 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
321 if (r != null) {
322 return r;
323 }
324 }
325 return null;
326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327
328 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 * Activity we have told the window manager to have key focus.
330 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700331 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700332 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 * List of intents that were used to start the most recent tasks.
334 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700335 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336
337 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700338 * Process management.
339 */
340 final ProcessList mProcessList = new ProcessList();
341
342 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 * All of the applications we currently have running organized by name.
344 * The keys are strings of the application package name (as
345 * returned by the package manager), and the keys are ApplicationRecord
346 * objects.
347 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700348 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349
350 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800351 * The currently running isolated processes.
352 */
353 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
354
355 /**
356 * Counter for assigning isolated process uids, to avoid frequently reusing the
357 * same ones.
358 */
359 int mNextIsolatedProcessUid = 0;
360
361 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700362 * The currently running heavy-weight process, if any.
363 */
364 ProcessRecord mHeavyWeightProcess = null;
365
366 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 * The last time that various processes have crashed.
368 */
369 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
370
371 /**
372 * Set of applications that we consider to be bad, and will reject
373 * incoming broadcasts from (which the user has no control over).
374 * Processes are added to this set when they have crashed twice within
375 * a minimum amount of time; they are removed from it when they are
376 * later restarted (hopefully due to some user action). The value is the
377 * time it was added to the list.
378 */
379 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
380
381 /**
382 * All of the processes we currently have running organized by pid.
383 * The keys are the pid running the application.
384 *
385 * <p>NOTE: This object is protected by its own lock, NOT the global
386 * activity manager lock!
387 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700388 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389
390 /**
391 * All of the processes that have been forced to be foreground. The key
392 * is the pid of the caller who requested it (we hold a death
393 * link on it).
394 */
395 abstract class ForegroundToken implements IBinder.DeathRecipient {
396 int pid;
397 IBinder token;
398 }
399 final SparseArray<ForegroundToken> mForegroundProcesses
400 = new SparseArray<ForegroundToken>();
401
402 /**
403 * List of records for processes that someone had tried to start before the
404 * system was ready. We don't start them at that point, but ensure they
405 * are started by the time booting is complete.
406 */
407 final ArrayList<ProcessRecord> mProcessesOnHold
408 = new ArrayList<ProcessRecord>();
409
410 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800411 * List of persistent applications that are in the process
412 * of being started.
413 */
414 final ArrayList<ProcessRecord> mPersistentStartingProcesses
415 = new ArrayList<ProcessRecord>();
416
417 /**
418 * Processes that are being forcibly torn down.
419 */
420 final ArrayList<ProcessRecord> mRemovedProcesses
421 = new ArrayList<ProcessRecord>();
422
423 /**
424 * List of running applications, sorted by recent usage.
425 * The first entry in the list is the least recently used.
426 * It contains ApplicationRecord objects. This list does NOT include
427 * any persistent application records (since we never want to exit them).
428 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800429 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800430 = new ArrayList<ProcessRecord>();
431
432 /**
433 * List of processes that should gc as soon as things are idle.
434 */
435 final ArrayList<ProcessRecord> mProcessesToGc
436 = new ArrayList<ProcessRecord>();
437
438 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800439 * This is the process holding what we currently consider to be
440 * the "home" activity.
441 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700442 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800443
444 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700445 * This is the process holding the activity the user last visited that
446 * is in a different process from the one they are currently in.
447 */
448 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800449
450 /**
451 * The time at which the previous process was last visible.
452 */
453 long mPreviousProcessVisibleTime;
454
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700455 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400456 * Packages that the user has asked to have run in screen size
457 * compatibility mode instead of filling the screen.
458 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700459 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400460
461 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 * Set of PendingResultRecord objects that are currently active.
463 */
464 final HashSet mPendingResultRecords = new HashSet();
465
466 /**
467 * Set of IntentSenderRecord objects that are currently active.
468 */
469 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
470 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
471
472 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800473 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700474 * already logged DropBox entries for. Guarded by itself. If
475 * something (rogue user app) forces this over
476 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
477 */
478 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
479 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
480
481 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700482 * Strict Mode background batched logging state.
483 *
484 * The string buffer is guarded by itself, and its lock is also
485 * used to determine if another batched write is already
486 * in-flight.
487 */
488 private final StringBuilder mStrictModeBuffer = new StringBuilder();
489
490 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800491 * Keeps track of all IIntentReceivers that have been registered for
492 * broadcasts. Hash keys are the receiver IBinder, hash value is
493 * a ReceiverList.
494 */
495 final HashMap mRegisteredReceivers = new HashMap();
496
497 /**
498 * Resolver for broadcast intents to registered receivers.
499 * Holds BroadcastFilter (subclass of IntentFilter).
500 */
501 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
502 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
503 @Override
504 protected boolean allowFilterResult(
505 BroadcastFilter filter, List<BroadcastFilter> dest) {
506 IBinder target = filter.receiverList.receiver.asBinder();
507 for (int i=dest.size()-1; i>=0; i--) {
508 if (dest.get(i).receiverList.receiver.asBinder() == target) {
509 return false;
510 }
511 }
512 return true;
513 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700514
515 @Override
516 protected String packageForFilter(BroadcastFilter filter) {
517 return filter.packageName;
518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800519 };
520
521 /**
522 * State of all active sticky broadcasts. Keys are the action of the
523 * sticky Intent, values are an ArrayList of all broadcasted intents with
524 * that action (which should usually be one).
525 */
526 final HashMap<String, ArrayList<Intent>> mStickyBroadcasts =
527 new HashMap<String, ArrayList<Intent>>();
528
Amith Yamasani742a6712011-05-04 14:49:28 -0700529 final ServiceMap mServiceMap = new ServiceMap();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530
531 /**
532 * All currently bound service connections. Keys are the IBinder of
533 * the client's IServiceConnection.
534 */
Dianne Hackborn43d9ac82010-08-25 15:06:25 -0700535 final HashMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections
536 = new HashMap<IBinder, ArrayList<ConnectionRecord>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800537
538 /**
539 * List of services that we have been asked to start,
540 * but haven't yet been able to. It is used to hold start requests
541 * while waiting for their corresponding application thread to get
542 * going.
543 */
544 final ArrayList<ServiceRecord> mPendingServices
545 = new ArrayList<ServiceRecord>();
546
547 /**
548 * List of services that are scheduled to restart following a crash.
549 */
550 final ArrayList<ServiceRecord> mRestartingServices
551 = new ArrayList<ServiceRecord>();
552
553 /**
554 * List of services that are in the process of being stopped.
555 */
556 final ArrayList<ServiceRecord> mStoppingServices
557 = new ArrayList<ServiceRecord>();
558
559 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700560 * Backup/restore process management
561 */
562 String mBackupAppName = null;
563 BackupRecord mBackupTarget = null;
564
565 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 * List of PendingThumbnailsRecord objects of clients who are still
567 * waiting to receive all of the thumbnails for a task.
568 */
569 final ArrayList mPendingThumbnails = new ArrayList();
570
571 /**
572 * List of HistoryRecord objects that have been finished and must
573 * still report back to a pending thumbnail receiver.
574 */
575 final ArrayList mCancelledThumbnails = new ArrayList();
576
Amith Yamasani742a6712011-05-04 14:49:28 -0700577 final ProviderMap mProviderMap = new ProviderMap();
578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 /**
580 * List of content providers who have clients waiting for them. The
581 * application is currently being launched and the provider will be
582 * removed from this list once it is published.
583 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700584 final ArrayList<ContentProviderRecord> mLaunchingProviders
585 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800586
587 /**
588 * Global set of specific Uri permissions that have been granted.
589 */
590 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
591 = new SparseArray<HashMap<Uri, UriPermission>>();
592
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800593 CoreSettingsObserver mCoreSettingsObserver;
594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 /**
596 * Thread-local storage used to carry caller permissions over through
597 * indirect content-provider access.
598 * @see #ActivityManagerService.openContentUri()
599 */
600 private class Identity {
601 public int pid;
602 public int uid;
603
604 Identity(int _pid, int _uid) {
605 pid = _pid;
606 uid = _uid;
607 }
608 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
611
612 /**
613 * All information we have collected about the runtime performance of
614 * any user id that can impact battery performance.
615 */
616 final BatteryStatsService mBatteryStatsService;
617
618 /**
619 * information about component usage
620 */
621 final UsageStatsService mUsageStatsService;
622
623 /**
624 * Current configuration information. HistoryRecord objects are given
625 * a reference to this object to indicate which configuration they are
626 * currently running in, so this object must be kept immutable.
627 */
628 Configuration mConfiguration = new Configuration();
629
630 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800631 * Current sequencing integer of the configuration, for skipping old
632 * configurations.
633 */
634 int mConfigurationSeq = 0;
635
636 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700637 * Hardware-reported OpenGLES version.
638 */
639 final int GL_ES_VERSION;
640
641 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 * List of initialization arguments to pass to all processes when binding applications to them.
643 * For example, references to the commonly used services.
644 */
645 HashMap<String, IBinder> mAppBindArgs;
646
647 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700648 * Temporary to avoid allocations. Protected by main lock.
649 */
650 final StringBuilder mStringBuilder = new StringBuilder(256);
651
652 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 * Used to control how we initialize the service.
654 */
655 boolean mStartRunning = false;
656 ComponentName mTopComponent;
657 String mTopAction;
658 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700659 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800660 boolean mSystemReady = false;
661 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700662 boolean mWaitingUpdate = false;
663 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700664 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700665 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800666
667 Context mContext;
668
669 int mFactoryTest;
670
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700671 boolean mCheckedForSetup;
672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800673 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700674 * The time at which we will allow normal application switches again,
675 * after a call to {@link #stopAppSwitches()}.
676 */
677 long mAppSwitchesAllowedTime;
678
679 /**
680 * This is set to true after the first switch after mAppSwitchesAllowedTime
681 * is set; any switches after that will clear the time.
682 */
683 boolean mDidAppSwitch;
684
685 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700686 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700687 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700688 long mLastPowerCheckRealtime;
689
690 /**
691 * Last time (in uptime) at which we checked for power usage.
692 */
693 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700694
695 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800696 * Set while we are wanting to sleep, to prevent any
697 * activities from being started/resumed.
698 */
699 boolean mSleeping = false;
700
701 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700702 * State of external calls telling us if the device is asleep.
703 */
704 boolean mWentToSleep = false;
705
706 /**
707 * State of external call telling us if the lock screen is shown.
708 */
709 boolean mLockScreenShown = false;
710
711 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700712 * Set if we are shutting down the system, similar to sleeping.
713 */
714 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715
716 /**
717 * Task identifier that activities are currently being started
718 * in. Incremented each time a new task is created.
719 * todo: Replace this with a TokenSpace class that generates non-repeating
720 * integers that won't wrap.
721 */
722 int mCurTask = 1;
723
724 /**
725 * Current sequence id for oom_adj computation traversal.
726 */
727 int mAdjSeq = 0;
728
729 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700730 * Current sequence id for process LRU updating.
731 */
732 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733
734 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700735 * Keep track of the number of service processes we last found, to
736 * determine on the next iteration which should be B services.
737 */
738 int mNumServiceProcs = 0;
739 int mNewNumServiceProcs = 0;
740
741 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 * System monitoring: number of processes that died since the last
743 * N procs were started.
744 */
745 int[] mProcDeaths = new int[20];
746
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700747 /**
748 * This is set if we had to do a delayed dexopt of an app before launching
749 * it, to increasing the ANR timeouts in that case.
750 */
751 boolean mDidDexOpt;
752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 String mDebugApp = null;
754 boolean mWaitForDebugger = false;
755 boolean mDebugTransient = false;
756 String mOrigDebugApp = null;
757 boolean mOrigWaitForDebugger = false;
758 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700759 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700760 String mProfileApp = null;
761 ProcessRecord mProfileProc = null;
762 String mProfileFile;
763 ParcelFileDescriptor mProfileFd;
764 int mProfileType = 0;
765 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800766 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700768 static class ProcessChangeItem {
769 static final int CHANGE_ACTIVITIES = 1<<0;
770 static final int CHANGE_IMPORTANCE= 1<<1;
771 int changes;
772 int uid;
773 int pid;
774 int importance;
775 boolean foregroundActivities;
776 }
777
Jeff Sharkeya4620792011-05-20 15:29:23 -0700778 final RemoteCallbackList<IProcessObserver> mProcessObservers
779 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700780 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
781
782 final ArrayList<ProcessChangeItem> mPendingProcessChanges
783 = new ArrayList<ProcessChangeItem>();
784 final ArrayList<ProcessChangeItem> mAvailProcessChanges
785 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 /**
788 * Callback of last caller to {@link #requestPss}.
789 */
790 Runnable mRequestPssCallback;
791
792 /**
793 * Remaining processes for which we are waiting results from the last
794 * call to {@link #requestPss}.
795 */
796 final ArrayList<ProcessRecord> mRequestPssList
797 = new ArrayList<ProcessRecord>();
798
799 /**
800 * Runtime statistics collection thread. This object's lock is used to
801 * protect all related state.
802 */
803 final Thread mProcessStatsThread;
804
805 /**
806 * Used to collect process stats when showing not responding dialog.
807 * Protected by mProcessStatsThread.
808 */
809 final ProcessStats mProcessStats = new ProcessStats(
810 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700811 final AtomicLong mLastCpuTime = new AtomicLong(0);
812 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 long mLastWriteTime = 0;
815
816 /**
817 * Set to true after the system has finished booting.
818 */
819 boolean mBooted = false;
820
Dianne Hackborn7d608422011-08-07 16:24:18 -0700821 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700822 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823
824 WindowManagerService mWindowManager;
825
826 static ActivityManagerService mSelf;
827 static ActivityThread mSystemThread;
828
829 private final class AppDeathRecipient implements IBinder.DeathRecipient {
830 final ProcessRecord mApp;
831 final int mPid;
832 final IApplicationThread mAppThread;
833
834 AppDeathRecipient(ProcessRecord app, int pid,
835 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800836 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 TAG, "New death recipient " + this
838 + " for thread " + thread.asBinder());
839 mApp = app;
840 mPid = pid;
841 mAppThread = thread;
842 }
843
844 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800845 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 TAG, "Death received in " + this
847 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 synchronized(ActivityManagerService.this) {
849 appDiedLocked(mApp, mPid, mAppThread);
850 }
851 }
852 }
853
854 static final int SHOW_ERROR_MSG = 1;
855 static final int SHOW_NOT_RESPONDING_MSG = 2;
856 static final int SHOW_FACTORY_ERROR_MSG = 3;
857 static final int UPDATE_CONFIGURATION_MSG = 4;
858 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
859 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 static final int SERVICE_TIMEOUT_MSG = 12;
861 static final int UPDATE_TIME_ZONE = 13;
862 static final int SHOW_UID_ERROR_MSG = 14;
863 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700865 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700866 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800867 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700868 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
869 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700870 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700871 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700872 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700873 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700874 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700875 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700876 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700877 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800879 static final int FIRST_ACTIVITY_STACK_MSG = 100;
880 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
881 static final int FIRST_COMPAT_MODE_MSG = 300;
882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700884 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700885 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886
887 final Handler mHandler = new Handler() {
888 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800889 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 //}
891
892 public void handleMessage(Message msg) {
893 switch (msg.what) {
894 case SHOW_ERROR_MSG: {
895 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800896 synchronized (ActivityManagerService.this) {
897 ProcessRecord proc = (ProcessRecord)data.get("app");
898 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800899 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 return;
901 }
902 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700903 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800904 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 d.show();
906 proc.crashDialog = d;
907 } else {
908 // The device is asleep, so just pretend that the user
909 // saw a crash dialog and hit "force quit".
910 res.set(0);
911 }
912 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700913
914 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 } break;
916 case SHOW_NOT_RESPONDING_MSG: {
917 synchronized (ActivityManagerService.this) {
918 HashMap data = (HashMap) msg.obj;
919 ProcessRecord proc = (ProcessRecord)data.get("app");
920 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800921 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 return;
923 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800924
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700925 Intent intent = new Intent("android.intent.action.ANR");
926 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800927 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
928 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700929 }
930 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800931 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700932 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800933
Justin Kohbc52ca22012-03-29 15:11:44 -0700934 if (mShowDialogs) {
935 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700936 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700937 d.show();
938 proc.anrDialog = d;
939 } else {
940 // Just kill the app if there is no dialog to be shown.
941 killAppAtUsersRequest(proc, null);
942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700944
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700945 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700947 case SHOW_STRICT_MODE_VIOLATION_MSG: {
948 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
949 synchronized (ActivityManagerService.this) {
950 ProcessRecord proc = (ProcessRecord) data.get("app");
951 if (proc == null) {
952 Slog.e(TAG, "App not found when showing strict mode dialog.");
953 break;
954 }
955 if (proc.crashDialog != null) {
956 Slog.e(TAG, "App already has strict mode dialog: " + proc);
957 return;
958 }
959 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700960 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700961 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
962 d.show();
963 proc.crashDialog = d;
964 } else {
965 // The device is asleep, so just pretend that the user
966 // saw a crash dialog and hit "force quit".
967 res.set(0);
968 }
969 }
970 ensureBootCompleted();
971 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800972 case SHOW_FACTORY_ERROR_MSG: {
973 Dialog d = new FactoryErrorDialog(
974 mContext, msg.getData().getCharSequence("msg"));
975 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700976 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 } break;
978 case UPDATE_CONFIGURATION_MSG: {
979 final ContentResolver resolver = mContext.getContentResolver();
980 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
981 } break;
982 case GC_BACKGROUND_PROCESSES_MSG: {
983 synchronized (ActivityManagerService.this) {
984 performAppGcsIfAppropriateLocked();
985 }
986 } break;
987 case WAIT_FOR_DEBUGGER_MSG: {
988 synchronized (ActivityManagerService.this) {
989 ProcessRecord app = (ProcessRecord)msg.obj;
990 if (msg.arg1 != 0) {
991 if (!app.waitedForDebugger) {
992 Dialog d = new AppWaitingForDebuggerDialog(
993 ActivityManagerService.this,
994 mContext, app);
995 app.waitDialog = d;
996 app.waitedForDebugger = true;
997 d.show();
998 }
999 } else {
1000 if (app.waitDialog != null) {
1001 app.waitDialog.dismiss();
1002 app.waitDialog = null;
1003 }
1004 }
1005 }
1006 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001008 if (mDidDexOpt) {
1009 mDidDexOpt = false;
1010 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
1011 nmsg.obj = msg.obj;
1012 mHandler.sendMessageDelayed(nmsg, SERVICE_TIMEOUT);
1013 return;
1014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 serviceTimeout((ProcessRecord)msg.obj);
1016 } break;
1017 case UPDATE_TIME_ZONE: {
1018 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001019 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1020 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 if (r.thread != null) {
1022 try {
1023 r.thread.updateTimeZone();
1024 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001025 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 }
1027 }
1028 }
1029 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001030 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001031 case CLEAR_DNS_CACHE: {
1032 synchronized (ActivityManagerService.this) {
1033 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1034 ProcessRecord r = mLruProcesses.get(i);
1035 if (r.thread != null) {
1036 try {
1037 r.thread.clearDnsCache();
1038 } catch (RemoteException ex) {
1039 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1040 }
1041 }
1042 }
1043 }
1044 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001045 case UPDATE_HTTP_PROXY: {
1046 ProxyProperties proxy = (ProxyProperties)msg.obj;
1047 String host = "";
1048 String port = "";
1049 String exclList = "";
1050 if (proxy != null) {
1051 host = proxy.getHost();
1052 port = Integer.toString(proxy.getPort());
1053 exclList = proxy.getExclusionList();
1054 }
1055 synchronized (ActivityManagerService.this) {
1056 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1057 ProcessRecord r = mLruProcesses.get(i);
1058 if (r.thread != null) {
1059 try {
1060 r.thread.setHttpProxy(host, port, exclList);
1061 } catch (RemoteException ex) {
1062 Slog.w(TAG, "Failed to update http proxy for: " +
1063 r.info.processName);
1064 }
1065 }
1066 }
1067 }
1068 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001070 String title = "System UIDs Inconsistent";
1071 String text = "UIDs on the system are inconsistent, you need to wipe your"
1072 + " data partition or your device will be unstable.";
1073 Log.e(TAG, title + ": " + text);
1074 if (mShowDialogs) {
1075 // XXX This is a temporary dialog, no need to localize.
1076 AlertDialog d = new BaseErrorDialog(mContext);
1077 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1078 d.setCancelable(false);
1079 d.setTitle(title);
1080 d.setMessage(text);
1081 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1082 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1083 mUidAlert = d;
1084 d.show();
1085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 } break;
1087 case IM_FEELING_LUCKY_MSG: {
1088 if (mUidAlert != null) {
1089 mUidAlert.dismiss();
1090 mUidAlert = null;
1091 }
1092 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001094 if (mDidDexOpt) {
1095 mDidDexOpt = false;
1096 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1097 nmsg.obj = msg.obj;
1098 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1099 return;
1100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 ProcessRecord app = (ProcessRecord)msg.obj;
1102 synchronized (ActivityManagerService.this) {
1103 processStartTimedOutLocked(app);
1104 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001105 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001106 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1107 synchronized (ActivityManagerService.this) {
1108 doPendingActivityLaunchesLocked(true);
1109 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001110 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001111 case KILL_APPLICATION_MSG: {
1112 synchronized (ActivityManagerService.this) {
1113 int uid = msg.arg1;
1114 boolean restart = (msg.arg2 == 1);
1115 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001116 forceStopPackageLocked(pkg, uid, restart, false, true, false,
1117 UserId.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001118 }
1119 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001120 case FINALIZE_PENDING_INTENT_MSG: {
1121 ((PendingIntentRecord)msg.obj).completeFinalize();
1122 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001123 case POST_HEAVY_NOTIFICATION_MSG: {
1124 INotificationManager inm = NotificationManager.getService();
1125 if (inm == null) {
1126 return;
1127 }
1128
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001129 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001130 ProcessRecord process = root.app;
1131 if (process == null) {
1132 return;
1133 }
1134
1135 try {
1136 Context context = mContext.createPackageContext(process.info.packageName, 0);
1137 String text = mContext.getString(R.string.heavy_weight_notification,
1138 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1139 Notification notification = new Notification();
1140 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1141 notification.when = 0;
1142 notification.flags = Notification.FLAG_ONGOING_EVENT;
1143 notification.tickerText = text;
1144 notification.defaults = 0; // please be quiet
1145 notification.sound = null;
1146 notification.vibrate = null;
1147 notification.setLatestEventInfo(context, text,
1148 mContext.getText(R.string.heavy_weight_notification_detail),
1149 PendingIntent.getActivity(mContext, 0, root.intent,
1150 PendingIntent.FLAG_CANCEL_CURRENT));
1151
1152 try {
1153 int[] outId = new int[1];
1154 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1155 notification, outId);
1156 } catch (RuntimeException e) {
1157 Slog.w(ActivityManagerService.TAG,
1158 "Error showing notification for heavy-weight app", e);
1159 } catch (RemoteException e) {
1160 }
1161 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001162 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001163 }
1164 } break;
1165 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1166 INotificationManager inm = NotificationManager.getService();
1167 if (inm == null) {
1168 return;
1169 }
1170 try {
1171 inm.cancelNotification("android",
1172 R.string.heavy_weight_notification);
1173 } catch (RuntimeException e) {
1174 Slog.w(ActivityManagerService.TAG,
1175 "Error canceling notification for service", e);
1176 } catch (RemoteException e) {
1177 }
1178 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001179 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1180 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001181 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001182 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001183 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1184 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001185 }
1186 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001187 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1188 synchronized (ActivityManagerService.this) {
1189 ActivityRecord ar = (ActivityRecord)msg.obj;
1190 if (mCompatModeDialog != null) {
1191 if (mCompatModeDialog.mAppInfo.packageName.equals(
1192 ar.info.applicationInfo.packageName)) {
1193 return;
1194 }
1195 mCompatModeDialog.dismiss();
1196 mCompatModeDialog = null;
1197 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001198 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001199 if (mCompatModePackages.getPackageAskCompatModeLocked(
1200 ar.packageName)) {
1201 int mode = mCompatModePackages.computeCompatModeLocked(
1202 ar.info.applicationInfo);
1203 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1204 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1205 mCompatModeDialog = new CompatModeDialog(
1206 ActivityManagerService.this, mContext,
1207 ar.info.applicationInfo);
1208 mCompatModeDialog.show();
1209 }
1210 }
1211 }
1212 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001213 break;
1214 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001215 case DISPATCH_PROCESSES_CHANGED: {
1216 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001217 break;
1218 }
1219 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001220 final int pid = msg.arg1;
1221 final int uid = msg.arg2;
1222 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001223 break;
1224 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001225 case REPORT_MEM_USAGE: {
1226 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1227 if (!isDebuggable) {
1228 return;
1229 }
1230 synchronized (ActivityManagerService.this) {
1231 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001232 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1233 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001234 // avoid spamming.
1235 return;
1236 }
1237 mLastMemUsageReportTime = now;
1238 }
1239 Thread thread = new Thread() {
1240 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001241 StringBuilder dropBuilder = new StringBuilder(1024);
1242 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001243 StringWriter oomSw = new StringWriter();
1244 PrintWriter oomPw = new PrintWriter(oomSw);
1245 StringWriter catSw = new StringWriter();
1246 PrintWriter catPw = new PrintWriter(catSw);
1247 String[] emptyArgs = new String[] { };
1248 StringBuilder tag = new StringBuilder(128);
1249 StringBuilder stack = new StringBuilder(128);
1250 tag.append("Low on memory -- ");
1251 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1252 tag, stack);
1253 dropBuilder.append(stack);
1254 dropBuilder.append('\n');
1255 dropBuilder.append('\n');
1256 String oomString = oomSw.toString();
1257 dropBuilder.append(oomString);
1258 dropBuilder.append('\n');
1259 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001260 try {
1261 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1262 "procrank", });
1263 final InputStreamReader converter = new InputStreamReader(
1264 proc.getInputStream());
1265 BufferedReader in = new BufferedReader(converter);
1266 String line;
1267 while (true) {
1268 line = in.readLine();
1269 if (line == null) {
1270 break;
1271 }
1272 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001273 logBuilder.append(line);
1274 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001275 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001276 dropBuilder.append(line);
1277 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001278 }
1279 converter.close();
1280 } catch (IOException e) {
1281 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001282 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001283 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001284 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001285 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001286 dumpServicesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001287 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001288 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001289 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001290 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001291 addErrorToDropBox("lowmem", null, "system_server", null,
1292 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001293 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001294 synchronized (ActivityManagerService.this) {
1295 long now = SystemClock.uptimeMillis();
1296 if (mLastMemUsageReportTime < now) {
1297 mLastMemUsageReportTime = now;
1298 }
1299 }
1300 }
1301 };
1302 thread.start();
1303 break;
1304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 }
1306 }
1307 };
1308
1309 public static void setSystemProcess() {
1310 try {
1311 ActivityManagerService m = mSelf;
1312
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001313 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001315 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001316 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 if (MONITOR_CPU_USAGE) {
1318 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 ServiceManager.addService("permission", new PermissionController(m));
1321
1322 ApplicationInfo info =
1323 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001324 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001325 mSystemThread.installSystemApplicationInfo(info);
1326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 synchronized (mSelf) {
1328 ProcessRecord app = mSelf.newProcessRecordLocked(
1329 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001330 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001332 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001333 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001334 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 synchronized (mSelf.mPidsSelfLocked) {
1336 mSelf.mPidsSelfLocked.put(app.pid, app);
1337 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001338 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
1340 } catch (PackageManager.NameNotFoundException e) {
1341 throw new RuntimeException(
1342 "Unable to find android system package", e);
1343 }
1344 }
1345
1346 public void setWindowManager(WindowManagerService wm) {
1347 mWindowManager = wm;
1348 }
1349
1350 public static final Context main(int factoryTest) {
1351 AThread thr = new AThread();
1352 thr.start();
1353
1354 synchronized (thr) {
1355 while (thr.mService == null) {
1356 try {
1357 thr.wait();
1358 } catch (InterruptedException e) {
1359 }
1360 }
1361 }
1362
1363 ActivityManagerService m = thr.mService;
1364 mSelf = m;
1365 ActivityThread at = ActivityThread.systemMain();
1366 mSystemThread = at;
1367 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001368 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 m.mContext = context;
1370 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001371 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372
1373 m.mBatteryStatsService.publish(context);
1374 m.mUsageStatsService.publish(context);
1375
1376 synchronized (thr) {
1377 thr.mReady = true;
1378 thr.notifyAll();
1379 }
1380
1381 m.startRunning(null, null, null, null);
1382
1383 return context;
1384 }
1385
1386 public static ActivityManagerService self() {
1387 return mSelf;
1388 }
1389
1390 static class AThread extends Thread {
1391 ActivityManagerService mService;
1392 boolean mReady = false;
1393
1394 public AThread() {
1395 super("ActivityManager");
1396 }
1397
1398 public void run() {
1399 Looper.prepare();
1400
1401 android.os.Process.setThreadPriority(
1402 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001403 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001404
1405 ActivityManagerService m = new ActivityManagerService();
1406
1407 synchronized (this) {
1408 mService = m;
1409 notifyAll();
1410 }
1411
1412 synchronized (this) {
1413 while (!mReady) {
1414 try {
1415 wait();
1416 } catch (InterruptedException e) {
1417 }
1418 }
1419 }
1420
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001421 // For debug builds, log event loop stalls to dropbox for analysis.
1422 if (StrictMode.conditionallyEnableDebugLogging()) {
1423 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1424 }
1425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 Looper.loop();
1427 }
1428 }
1429
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 static class MemBinder extends Binder {
1431 ActivityManagerService mActivityManagerService;
1432 MemBinder(ActivityManagerService activityManagerService) {
1433 mActivityManagerService = activityManagerService;
1434 }
1435
1436 @Override
1437 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001438 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1439 != PackageManager.PERMISSION_GRANTED) {
1440 pw.println("Permission Denial: can't dump meminfo from from pid="
1441 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1442 + " without permission " + android.Manifest.permission.DUMP);
1443 return;
1444 }
1445
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001446 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001447 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 }
1449 }
1450
Chet Haase9c1e23b2011-03-24 10:51:31 -07001451 static class GraphicsBinder extends Binder {
1452 ActivityManagerService mActivityManagerService;
1453 GraphicsBinder(ActivityManagerService activityManagerService) {
1454 mActivityManagerService = activityManagerService;
1455 }
1456
1457 @Override
1458 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001459 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1460 != PackageManager.PERMISSION_GRANTED) {
1461 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1462 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1463 + " without permission " + android.Manifest.permission.DUMP);
1464 return;
1465 }
1466
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001467 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001468 }
1469 }
1470
Jeff Brown6754ba22011-12-14 20:20:01 -08001471 static class DbBinder extends Binder {
1472 ActivityManagerService mActivityManagerService;
1473 DbBinder(ActivityManagerService activityManagerService) {
1474 mActivityManagerService = activityManagerService;
1475 }
1476
1477 @Override
1478 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1479 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1480 != PackageManager.PERMISSION_GRANTED) {
1481 pw.println("Permission Denial: can't dump dbinfo from from pid="
1482 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1483 + " without permission " + android.Manifest.permission.DUMP);
1484 return;
1485 }
1486
1487 mActivityManagerService.dumpDbInfo(fd, pw, args);
1488 }
1489 }
1490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 static class CpuBinder extends Binder {
1492 ActivityManagerService mActivityManagerService;
1493 CpuBinder(ActivityManagerService activityManagerService) {
1494 mActivityManagerService = activityManagerService;
1495 }
1496
1497 @Override
1498 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001499 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1500 != PackageManager.PERMISSION_GRANTED) {
1501 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1502 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1503 + " without permission " + android.Manifest.permission.DUMP);
1504 return;
1505 }
1506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001508 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1509 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1510 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512 }
1513 }
1514
1515 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001516 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001517
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001518 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1519 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1520 mBroadcastQueues[0] = mFgBroadcastQueue;
1521 mBroadcastQueues[1] = mBgBroadcastQueue;
1522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 File dataDir = Environment.getDataDirectory();
1524 File systemDir = new File(dataDir, "system");
1525 systemDir.mkdirs();
1526 mBatteryStatsService = new BatteryStatsService(new File(
1527 systemDir, "batterystats.bin").toString());
1528 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001529 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001530 mOnBattery = DEBUG_POWER ? true
1531 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001532 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001534 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001535 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001536 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537
Jack Palevichb90d28c2009-07-22 15:35:24 -07001538 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1539 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1540
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001541 mConfiguration.setToDefaults();
1542 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001543 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 mProcessStats.init();
1545
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001546 mCompatModePackages = new CompatModePackages(this, systemDir);
1547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 // Add ourself to the Watchdog monitors.
1549 Watchdog.getInstance().addMonitor(this);
1550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 mProcessStatsThread = new Thread("ProcessStats") {
1552 public void run() {
1553 while (true) {
1554 try {
1555 try {
1556 synchronized(this) {
1557 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001558 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001560 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 // + ", write delay=" + nextWriteDelay);
1562 if (nextWriteDelay < nextCpuDelay) {
1563 nextCpuDelay = nextWriteDelay;
1564 }
1565 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001566 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 this.wait(nextCpuDelay);
1568 }
1569 }
1570 } catch (InterruptedException e) {
1571 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 updateCpuStatsNow();
1573 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001574 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 }
1576 }
1577 }
1578 };
1579 mProcessStatsThread.start();
1580 }
1581
1582 @Override
1583 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1584 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001585 if (code == SYSPROPS_TRANSACTION) {
1586 // We need to tell all apps about the system property change.
1587 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1588 synchronized(this) {
1589 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1590 final int NA = apps.size();
1591 for (int ia=0; ia<NA; ia++) {
1592 ProcessRecord app = apps.valueAt(ia);
1593 if (app.thread != null) {
1594 procs.add(app.thread.asBinder());
1595 }
1596 }
1597 }
1598 }
1599
1600 int N = procs.size();
1601 for (int i=0; i<N; i++) {
1602 Parcel data2 = Parcel.obtain();
1603 try {
1604 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1605 } catch (RemoteException e) {
1606 }
1607 data2.recycle();
1608 }
1609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 try {
1611 return super.onTransact(code, data, reply, flags);
1612 } catch (RuntimeException e) {
1613 // The activity manager only throws security exceptions, so let's
1614 // log all others.
1615 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001616 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 }
1618 throw e;
1619 }
1620 }
1621
1622 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001623 final long now = SystemClock.uptimeMillis();
1624 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1625 return;
1626 }
1627 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1628 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 mProcessStatsThread.notify();
1630 }
1631 }
1632 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 void updateCpuStatsNow() {
1635 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001636 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 final long now = SystemClock.uptimeMillis();
1638 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001641 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1642 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 haveNewCpuStats = true;
1644 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001645 //Slog.i(TAG, mProcessStats.printCurrentState());
1646 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 // + mProcessStats.getTotalCpuPercent() + "%");
1648
Joe Onorato8a9b2202010-02-26 18:56:32 -08001649 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 if ("true".equals(SystemProperties.get("events.cpu"))) {
1651 int user = mProcessStats.getLastUserTime();
1652 int system = mProcessStats.getLastSystemTime();
1653 int iowait = mProcessStats.getLastIoWaitTime();
1654 int irq = mProcessStats.getLastIrqTime();
1655 int softIrq = mProcessStats.getLastSoftIrqTime();
1656 int idle = mProcessStats.getLastIdleTime();
1657
1658 int total = user + system + iowait + irq + softIrq + idle;
1659 if (total == 0) total = 1;
1660
Doug Zongker2bec3d42009-12-04 12:52:44 -08001661 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 ((user+system+iowait+irq+softIrq) * 100) / total,
1663 (user * 100) / total,
1664 (system * 100) / total,
1665 (iowait * 100) / total,
1666 (irq * 100) / total,
1667 (softIrq * 100) / total);
1668 }
1669 }
1670
Amith Yamasanie43530a2009-08-21 13:11:37 -07001671 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001672 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001673 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 synchronized(mPidsSelfLocked) {
1675 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001676 if (mOnBattery) {
1677 int perc = bstats.startAddingCpuLocked();
1678 int totalUTime = 0;
1679 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001680 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001682 ProcessStats.Stats st = mProcessStats.getStats(i);
1683 if (!st.working) {
1684 continue;
1685 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001687 int otherUTime = (st.rel_utime*perc)/100;
1688 int otherSTime = (st.rel_stime*perc)/100;
1689 totalUTime += otherUTime;
1690 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 if (pr != null) {
1692 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001693 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1694 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001695 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001696 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001697 } else {
1698 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001699 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001700 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001701 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1702 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001703 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 }
1706 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001707 bstats.finishAddingCpuLocked(perc, totalUTime,
1708 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 }
1710 }
1711 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1714 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001715 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 }
1717 }
1718 }
1719 }
1720
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001721 @Override
1722 public void batteryNeedsCpuUpdate() {
1723 updateCpuStatsNow();
1724 }
1725
1726 @Override
1727 public void batteryPowerChanged(boolean onBattery) {
1728 // When plugging in, update the CPU stats first before changing
1729 // the plug state.
1730 updateCpuStatsNow();
1731 synchronized (this) {
1732 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001733 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001734 }
1735 }
1736 }
1737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 /**
1739 * Initialize the application bind args. These are passed to each
1740 * process when the bindApplication() IPC is sent to the process. They're
1741 * lazily setup to make sure the services are running when they're asked for.
1742 */
1743 private HashMap<String, IBinder> getCommonServicesLocked() {
1744 if (mAppBindArgs == null) {
1745 mAppBindArgs = new HashMap<String, IBinder>();
1746
1747 // Setup the application init args
1748 mAppBindArgs.put("package", ServiceManager.getService("package"));
1749 mAppBindArgs.put("window", ServiceManager.getService("window"));
1750 mAppBindArgs.put(Context.ALARM_SERVICE,
1751 ServiceManager.getService(Context.ALARM_SERVICE));
1752 }
1753 return mAppBindArgs;
1754 }
1755
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001756 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 if (mFocusedActivity != r) {
1758 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001759 if (r != null) {
1760 mWindowManager.setFocusedApp(r.appToken, true);
1761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 }
1763 }
1764
Dianne Hackborn906497c2010-05-10 15:57:38 -07001765 private final void updateLruProcessInternalLocked(ProcessRecord app,
1766 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001768 int lrui = mLruProcesses.indexOf(app);
1769 if (lrui >= 0) mLruProcesses.remove(lrui);
1770
1771 int i = mLruProcesses.size()-1;
1772 int skipTop = 0;
1773
Dianne Hackborn906497c2010-05-10 15:57:38 -07001774 app.lruSeq = mLruSeq;
1775
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001776 // compute the new weight for this process.
1777 if (updateActivityTime) {
1778 app.lastActivityTime = SystemClock.uptimeMillis();
1779 }
1780 if (app.activities.size() > 0) {
1781 // If this process has activities, we more strongly want to keep
1782 // it around.
1783 app.lruWeight = app.lastActivityTime;
1784 } else if (app.pubProviders.size() > 0) {
1785 // If this process contains content providers, we want to keep
1786 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001787 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001788 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001789 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001790 } else {
1791 // If this process doesn't have activities, we less strongly
1792 // want to keep it around, and generally want to avoid getting
1793 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001794 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001795 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001796 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001797 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001798
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001799 while (i >= 0) {
1800 ProcessRecord p = mLruProcesses.get(i);
1801 // If this app shouldn't be in front of the first N background
1802 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001803 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001804 skipTop--;
1805 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001806 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001807 mLruProcesses.add(i+1, app);
1808 break;
1809 }
1810 i--;
1811 }
1812 if (i < 0) {
1813 mLruProcesses.add(0, app);
1814 }
1815
Dianne Hackborn906497c2010-05-10 15:57:38 -07001816 // If the app is currently using a content provider or service,
1817 // bump those processes as well.
1818 if (app.connections.size() > 0) {
1819 for (ConnectionRecord cr : app.connections) {
1820 if (cr.binding != null && cr.binding.service != null
1821 && cr.binding.service.app != null
1822 && cr.binding.service.app.lruSeq != mLruSeq) {
1823 updateLruProcessInternalLocked(cr.binding.service.app, oomAdj,
1824 updateActivityTime, i+1);
1825 }
1826 }
1827 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001828 for (int j=app.conProviders.size()-1; j>=0; j--) {
1829 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1830 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
1831 updateLruProcessInternalLocked(cpr.proc, oomAdj,
1832 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001833 }
1834 }
1835
Joe Onorato8a9b2202010-02-26 18:56:32 -08001836 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 if (oomAdj) {
1838 updateOomAdjLocked();
1839 }
1840 }
1841
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001842 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001843 boolean oomAdj, boolean updateActivityTime) {
1844 mLruSeq++;
1845 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1846 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001847
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001848 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001850 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001851 // The system gets to run in any process. If there are multiple
1852 // processes with the same uid, just pick the first (this
1853 // should never happen).
1854 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1855 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001856 if (procs == null) return null;
1857 final int N = procs.size();
1858 for (int i = 0; i < N; i++) {
1859 if (UserId.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
1860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001861 }
1862 ProcessRecord proc = mProcessNames.get(processName, uid);
1863 return proc;
1864 }
1865
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001866 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001867 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001868 try {
1869 if (pm.performDexOpt(packageName)) {
1870 mDidDexOpt = true;
1871 }
1872 } catch (RemoteException e) {
1873 }
1874 }
1875
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001876 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 int transit = mWindowManager.getPendingAppTransition();
1878 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1879 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1880 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1881 }
1882
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001883 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001885 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1886 boolean isolated) {
1887 ProcessRecord app;
1888 if (!isolated) {
1889 app = getProcessRecordLocked(processName, info.uid);
1890 } else {
1891 // If this is an isolated process, it can't re-use an existing process.
1892 app = null;
1893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 // We don't have to do anything more if:
1895 // (1) There is an existing application record; and
1896 // (2) The caller doesn't think it is dead, OR there is no thread
1897 // object attached to it so we know it couldn't have crashed; and
1898 // (3) There is a pid assigned to it, so it is either starting or
1899 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001900 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 + " app=" + app + " knownToBeDead=" + knownToBeDead
1902 + " thread=" + (app != null ? app.thread : null)
1903 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001904 if (app != null && app.pid > 0) {
1905 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001906 // We already have the app running, or are waiting for it to
1907 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001908 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001909 // If this is a new package in the process, add the package to the list
1910 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001911 return app;
1912 } else {
1913 // An application record is attached to a previous process,
1914 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001915 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001916 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001918 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 String hostingNameStr = hostingName != null
1921 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001922
1923 if (!isolated) {
1924 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1925 // If we are in the background, then check to see if this process
1926 // is bad. If so, we will just silently fail.
1927 if (mBadProcesses.get(info.processName, info.uid) != null) {
1928 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1929 + "/" + info.processName);
1930 return null;
1931 }
1932 } else {
1933 // When the user is explicitly starting a process, then clear its
1934 // crash count so that we won't make it bad until they see at
1935 // least one crash dialog again, and make the process good again
1936 // if it had been bad.
1937 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001938 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001939 mProcessCrashTimes.remove(info.processName, info.uid);
1940 if (mBadProcesses.get(info.processName, info.uid) != null) {
1941 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1942 info.processName);
1943 mBadProcesses.remove(info.processName, info.uid);
1944 if (app != null) {
1945 app.bad = false;
1946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 }
1948 }
1949 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001952 app = newProcessRecordLocked(null, info, processName, isolated);
1953 if (app == null) {
1954 Slog.w(TAG, "Failed making new process record for "
1955 + processName + "/" + info.uid + " isolated=" + isolated);
1956 return null;
1957 }
1958 mProcessNames.put(processName, app.uid, app);
1959 if (isolated) {
1960 mIsolatedProcesses.put(app.uid, app);
1961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 } else {
1963 // If this is a new package in the process, add the package to the list
1964 app.addPackage(info.packageName);
1965 }
1966
1967 // If the system is not ready yet, then hold off on starting this
1968 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001969 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001970 && !isAllowedWhileBooting(info)
1971 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 if (!mProcessesOnHold.contains(app)) {
1973 mProcessesOnHold.add(app);
1974 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001975 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 return app;
1977 }
1978
1979 startProcessLocked(app, hostingType, hostingNameStr);
1980 return (app.pid != 0) ? app : null;
1981 }
1982
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001983 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1984 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1985 }
1986
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 private final void startProcessLocked(ProcessRecord app,
1988 String hostingType, String hostingNameStr) {
1989 if (app.pid > 0 && app.pid != MY_PID) {
1990 synchronized (mPidsSelfLocked) {
1991 mPidsSelfLocked.remove(app.pid);
1992 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1993 }
1994 app.pid = 0;
1995 }
1996
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001997 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1998 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 mProcessesOnHold.remove(app);
2000
2001 updateCpuStats();
2002
2003 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2004 mProcDeaths[0] = 0;
2005
2006 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002007 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002009 int[] gids = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002010 if (!app.isolated) {
2011 try {
2012 gids = mContext.getPackageManager().getPackageGids(
2013 app.info.packageName);
2014 } catch (PackageManager.NameNotFoundException e) {
2015 Slog.w(TAG, "Unable to retrieve gids", e);
2016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 }
2018 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2019 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2020 && mTopComponent != null
2021 && app.processName.equals(mTopComponent.getPackageName())) {
2022 uid = 0;
2023 }
2024 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2025 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2026 uid = 0;
2027 }
2028 }
2029 int debugFlags = 0;
2030 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2031 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002032 // Also turn on CheckJNI for debuggable apps. It's quite
2033 // awkward to turn on otherwise.
2034 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002036 // Run the app in safe mode if its manifest requests so or the
2037 // system is booted in safe mode.
2038 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2039 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002040 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2043 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2044 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002045 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2046 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 if ("1".equals(SystemProperties.get("debug.assert"))) {
2049 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2050 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002051
2052 // Start the process. It will either succeed and return a result containing
2053 // the PID of the new process, or else throw a RuntimeException.
2054 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Elliott Hughese1dfcb72011-07-08 11:08:07 -07002055 app.processName, uid, uid, gids, debugFlags,
2056 app.info.targetSdkVersion, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2059 synchronized (bs) {
2060 if (bs.isOnBattery()) {
2061 app.batteryStats.incStartsLocked();
2062 }
2063 }
2064
Jeff Brown3f9dd282011-07-08 20:02:19 -07002065 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 app.processName, hostingType,
2067 hostingNameStr != null ? hostingNameStr : "");
2068
2069 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002070 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002073 StringBuilder buf = mStringBuilder;
2074 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 buf.append("Start proc ");
2076 buf.append(app.processName);
2077 buf.append(" for ");
2078 buf.append(hostingType);
2079 if (hostingNameStr != null) {
2080 buf.append(" ");
2081 buf.append(hostingNameStr);
2082 }
2083 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002084 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 buf.append(" uid=");
2086 buf.append(uid);
2087 buf.append(" gids={");
2088 if (gids != null) {
2089 for (int gi=0; gi<gids.length; gi++) {
2090 if (gi != 0) buf.append(", ");
2091 buf.append(gids[gi]);
2092
2093 }
2094 }
2095 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002096 Slog.i(TAG, buf.toString());
Jeff Brown3f9dd282011-07-08 20:02:19 -07002097 app.pid = startResult.pid;
2098 app.usingWrapper = startResult.usingWrapper;
2099 app.removed = false;
2100 synchronized (mPidsSelfLocked) {
2101 this.mPidsSelfLocked.put(startResult.pid, app);
2102 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2103 msg.obj = app;
2104 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2105 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 }
2107 } catch (RuntimeException e) {
2108 // XXX do better error recovery.
2109 app.pid = 0;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002110 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 }
2112 }
2113
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002114 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 if (resumed) {
2116 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2117 } else {
2118 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2119 }
2120 }
2121
Amith Yamasani742a6712011-05-04 14:49:28 -07002122 boolean startHomeActivityLocked(int userId) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002123 if (mHeadless) {
2124 // Added because none of the other calls to ensureBootCompleted seem to fire
2125 // when running headless.
2126 ensureBootCompleted();
2127 return false;
2128 }
2129
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002130 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2131 && mTopAction == null) {
2132 // We are running in factory test mode, but unable to find
2133 // the factory test app, so just sit around displaying the
2134 // error message and don't try to start anything.
2135 return false;
2136 }
2137 Intent intent = new Intent(
2138 mTopAction,
2139 mTopData != null ? Uri.parse(mTopData) : null);
2140 intent.setComponent(mTopComponent);
2141 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2142 intent.addCategory(Intent.CATEGORY_HOME);
2143 }
2144 ActivityInfo aInfo =
2145 intent.resolveActivityInfo(mContext.getPackageManager(),
2146 STOCK_PM_FLAGS);
2147 if (aInfo != null) {
2148 intent.setComponent(new ComponentName(
2149 aInfo.applicationInfo.packageName, aInfo.name));
2150 // Don't do this if the home app is currently being
2151 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002152 aInfo = new ActivityInfo(aInfo);
2153 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002154 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2155 aInfo.applicationInfo.uid);
2156 if (app == null || app.instrumentationClass == null) {
2157 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002158 mMainStack.startActivityLocked(null, intent, null, aInfo,
2159 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002160 }
2161 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002162
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002163 return true;
2164 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002165
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002166 /**
2167 * Starts the "new version setup screen" if appropriate.
2168 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002169 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002170 // Only do this once per boot.
2171 if (mCheckedForSetup) {
2172 return;
2173 }
2174
2175 // We will show this screen if the current one is a different
2176 // version than the last one shown, and we are not running in
2177 // low-level factory test mode.
2178 final ContentResolver resolver = mContext.getContentResolver();
2179 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2180 Settings.Secure.getInt(resolver,
2181 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2182 mCheckedForSetup = true;
2183
2184 // See if we should be showing the platform update setup UI.
2185 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2186 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2187 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2188
2189 // We don't allow third party apps to replace this.
2190 ResolveInfo ri = null;
2191 for (int i=0; ris != null && i<ris.size(); i++) {
2192 if ((ris.get(i).activityInfo.applicationInfo.flags
2193 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2194 ri = ris.get(i);
2195 break;
2196 }
2197 }
2198
2199 if (ri != null) {
2200 String vers = ri.activityInfo.metaData != null
2201 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2202 : null;
2203 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2204 vers = ri.activityInfo.applicationInfo.metaData.getString(
2205 Intent.METADATA_SETUP_VERSION);
2206 }
2207 String lastVers = Settings.Secure.getString(
2208 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2209 if (vers != null && !vers.equals(lastVers)) {
2210 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2211 intent.setComponent(new ComponentName(
2212 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002213 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2214 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002215 }
2216 }
2217 }
2218 }
2219
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002220 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002221 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002222 }
2223
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002224 void enforceNotIsolatedCaller(String caller) {
2225 if (UserId.isIsolated(Binder.getCallingUid())) {
2226 throw new SecurityException("Isolated process not allowed to call " + caller);
2227 }
2228 }
2229
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002230 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002231 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002232 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002233 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2234 }
2235 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002236
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002237 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002238 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2239 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002240 synchronized (this) {
2241 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2242 }
2243 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002244
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002245 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002246 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002247 synchronized (this) {
2248 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2249 }
2250 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002251
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002252 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002253 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2254 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002255 synchronized (this) {
2256 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002257 }
2258 }
2259
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002260 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002261 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002262 synchronized (this) {
2263 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2264 }
2265 }
2266
2267 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002268 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2269 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002270 synchronized (this) {
2271 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2272 }
2273 }
2274
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002275 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002276 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002277 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002278 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002280 private void dispatchProcessesChanged() {
2281 int N;
2282 synchronized (this) {
2283 N = mPendingProcessChanges.size();
2284 if (mActiveProcessChanges.length < N) {
2285 mActiveProcessChanges = new ProcessChangeItem[N];
2286 }
2287 mPendingProcessChanges.toArray(mActiveProcessChanges);
2288 mAvailProcessChanges.addAll(mPendingProcessChanges);
2289 mPendingProcessChanges.clear();
2290 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2291 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002292 int i = mProcessObservers.beginBroadcast();
2293 while (i > 0) {
2294 i--;
2295 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2296 if (observer != null) {
2297 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002298 for (int j=0; j<N; j++) {
2299 ProcessChangeItem item = mActiveProcessChanges[j];
2300 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2301 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2302 + item.pid + " uid=" + item.uid + ": "
2303 + item.foregroundActivities);
2304 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2305 item.foregroundActivities);
2306 }
2307 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2308 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2309 + item.pid + " uid=" + item.uid + ": " + item.importance);
2310 observer.onImportanceChanged(item.pid, item.uid,
2311 item.importance);
2312 }
2313 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002314 } catch (RemoteException e) {
2315 }
2316 }
2317 }
2318 mProcessObservers.finishBroadcast();
2319 }
2320
2321 private void dispatchProcessDied(int pid, int uid) {
2322 int i = mProcessObservers.beginBroadcast();
2323 while (i > 0) {
2324 i--;
2325 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2326 if (observer != null) {
2327 try {
2328 observer.onProcessDied(pid, uid);
2329 } catch (RemoteException e) {
2330 }
2331 }
2332 }
2333 mProcessObservers.finishBroadcast();
2334 }
2335
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002336 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002337 final int N = mPendingActivityLaunches.size();
2338 if (N <= 0) {
2339 return;
2340 }
2341 for (int i=0; i<N; i++) {
2342 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002343 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002344 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002345 }
2346 mPendingActivityLaunches.clear();
2347 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002348
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002349 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002350 Intent intent, String resolvedType, IBinder resultTo,
2351 String resultWho, int requestCode, int startFlags,
2352 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002353 enforceNotIsolatedCaller("startActivity");
Amith Yamasani742a6712011-05-04 14:49:28 -07002354 int userId = 0;
2355 if (intent.getCategories() != null && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2356 // Requesting home, set the identity to the current user
2357 // HACK!
2358 userId = mCurrentUserId;
2359 } else {
2360 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2361 // the current user's userId
2362 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2363 userId = 0;
2364 } else {
2365 userId = Binder.getOrigCallingUser();
2366 }
2367 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002368 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002369 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2370 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002371 }
2372
2373 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002374 Intent intent, String resolvedType, IBinder resultTo,
2375 String resultWho, int requestCode, int startFlags, String profileFile,
2376 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002377 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002378 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002379 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002380 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002381 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2382 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002383 return res;
2384 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002385
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002386 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002387 Intent intent, String resolvedType, IBinder resultTo,
2388 String resultWho, int requestCode, int startFlags, Configuration config,
2389 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002390 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002391 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002392 resultTo, resultWho, requestCode, startFlags,
2393 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002394 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002395 }
2396
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002397 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002398 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002399 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002400 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002401 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002402 // Refuse possible leaked file descriptors
2403 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2404 throw new IllegalArgumentException("File descriptors passed in Intent");
2405 }
2406
2407 IIntentSender sender = intent.getTarget();
2408 if (!(sender instanceof PendingIntentRecord)) {
2409 throw new IllegalArgumentException("Bad PendingIntent object");
2410 }
2411
2412 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002413
2414 synchronized (this) {
2415 // If this is coming from the currently resumed activity, it is
2416 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002417 if (mMainStack.mResumedActivity != null
2418 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002419 Binder.getCallingUid()) {
2420 mAppSwitchesAllowedTime = 0;
2421 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002422 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002423 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2424 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002425 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002426 }
2427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002429 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 // Refuse possible leaked file descriptors
2431 if (intent != null && intent.hasFileDescriptors() == true) {
2432 throw new IllegalArgumentException("File descriptors passed in Intent");
2433 }
2434
2435 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002436 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2437 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002438 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 return false;
2440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 if (r.app == null || r.app.thread == null) {
2442 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002443 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 return false;
2445 }
2446 intent = new Intent(intent);
2447 // The caller is not allowed to change the data.
2448 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2449 // And we are resetting to find the next component...
2450 intent.setComponent(null);
2451
2452 ActivityInfo aInfo = null;
2453 try {
2454 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002455 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002457 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
2458 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459
2460 // Look for the original activity in the list...
2461 final int N = resolves != null ? resolves.size() : 0;
2462 for (int i=0; i<N; i++) {
2463 ResolveInfo rInfo = resolves.get(i);
2464 if (rInfo.activityInfo.packageName.equals(r.packageName)
2465 && rInfo.activityInfo.name.equals(r.info.name)) {
2466 // We found the current one... the next matching is
2467 // after it.
2468 i++;
2469 if (i<N) {
2470 aInfo = resolves.get(i).activityInfo;
2471 }
2472 break;
2473 }
2474 }
2475 } catch (RemoteException e) {
2476 }
2477
2478 if (aInfo == null) {
2479 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002480 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 return false;
2482 }
2483
2484 intent.setComponent(new ComponentName(
2485 aInfo.applicationInfo.packageName, aInfo.name));
2486 intent.setFlags(intent.getFlags()&~(
2487 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2488 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2489 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2490 Intent.FLAG_ACTIVITY_NEW_TASK));
2491
2492 // Okay now we need to start the new activity, replacing the
2493 // currently running activity. This is a little tricky because
2494 // we want to start the new one as if the current one is finished,
2495 // but not finish the current one first so that there is no flicker.
2496 // And thus...
2497 final boolean wasFinishing = r.finishing;
2498 r.finishing = true;
2499
2500 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002501 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 final String resultWho = r.resultWho;
2503 final int requestCode = r.requestCode;
2504 r.resultTo = null;
2505 if (resultTo != null) {
2506 resultTo.removeResultsLocked(r, resultWho, requestCode);
2507 }
2508
2509 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002510 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002511 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2512 resultWho, requestCode, -1, r.launchedFromUid, 0,
2513 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 Binder.restoreCallingIdentity(origId);
2515
2516 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002517 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 return false;
2519 }
2520 return true;
2521 }
2522 }
2523
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002524 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002526 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002527
2528 // This is so super not safe, that only the system (or okay root)
2529 // can do it.
Amith Yamasani742a6712011-05-04 14:49:28 -07002530 int userId = Binder.getOrigCallingUser();
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002531 final int callingUid = Binder.getCallingUid();
2532 if (callingUid != 0 && callingUid != Process.myUid()) {
2533 throw new SecurityException(
2534 "startActivityInPackage only available to the system");
2535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536
Amith Yamasani742a6712011-05-04 14:49:28 -07002537 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002538 resultTo, resultWho, requestCode, startFlags,
2539 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002540 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002541 }
2542
2543 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002544 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002545 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002546 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002547 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002548 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002549 }
2550
2551 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002552 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2553 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002554
2555 // This is so super not safe, that only the system (or okay root)
2556 // can do it.
2557 final int callingUid = Binder.getCallingUid();
2558 if (callingUid != 0 && callingUid != Process.myUid()) {
2559 throw new SecurityException(
2560 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002562 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002563 options, UserId.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002564 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 }
2566
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002567 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002569 // Quick case: check if the top-most recent task is the same.
2570 if (N > 0 && mRecentTasks.get(0) == task) {
2571 return;
2572 }
2573 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 for (int i=0; i<N; i++) {
2575 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002576 if (task.userId == tr.userId
2577 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2578 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 mRecentTasks.remove(i);
2580 i--;
2581 N--;
2582 if (task.intent == null) {
2583 // If the new recent task we are adding is not fully
2584 // specified, then replace it with the existing recent task.
2585 task = tr;
2586 }
2587 }
2588 }
2589 if (N >= MAX_RECENT_TASKS) {
2590 mRecentTasks.remove(N-1);
2591 }
2592 mRecentTasks.add(0, task);
2593 }
2594
2595 public void setRequestedOrientation(IBinder token,
2596 int requestedOrientation) {
2597 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002598 ActivityRecord r = mMainStack.isInStackLocked(token);
2599 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 return;
2601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002603 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002605 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002606 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 if (config != null) {
2608 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002609 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002610 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 }
2612 }
2613 Binder.restoreCallingIdentity(origId);
2614 }
2615 }
2616
2617 public int getRequestedOrientation(IBinder token) {
2618 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002619 ActivityRecord r = mMainStack.isInStackLocked(token);
2620 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2622 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002623 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 }
2625 }
2626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 /**
2628 * This is the internal entry point for handling Activity.finish().
2629 *
2630 * @param token The Binder token referencing the Activity we want to finish.
2631 * @param resultCode Result code, if any, from this Activity.
2632 * @param resultData Result data (Intent), if any, from this Activity.
2633 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002634 * @return Returns true if the activity successfully finished, or false if it is still running.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 */
2636 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2637 // Refuse possible leaked file descriptors
2638 if (resultData != null && resultData.hasFileDescriptors() == true) {
2639 throw new IllegalArgumentException("File descriptors passed in Intent");
2640 }
2641
2642 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002643 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002645 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 if (next != null) {
2647 // ask watcher if this is allowed
2648 boolean resumeOK = true;
2649 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002650 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002652 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 }
2654
2655 if (!resumeOK) {
2656 return false;
2657 }
2658 }
2659 }
2660 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002661 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 resultData, "app-request");
2663 Binder.restoreCallingIdentity(origId);
2664 return res;
2665 }
2666 }
2667
Dianne Hackborn860755f2010-06-03 18:47:52 -07002668 public final void finishHeavyWeightApp() {
2669 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2670 != PackageManager.PERMISSION_GRANTED) {
2671 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2672 + Binder.getCallingPid()
2673 + ", uid=" + Binder.getCallingUid()
2674 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2675 Slog.w(TAG, msg);
2676 throw new SecurityException(msg);
2677 }
2678
2679 synchronized(this) {
2680 if (mHeavyWeightProcess == null) {
2681 return;
2682 }
2683
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002684 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002685 mHeavyWeightProcess.activities);
2686 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002687 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002688 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002689 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002690 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002691 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002692 null, "finish-heavy");
2693 }
2694 }
2695 }
2696
2697 mHeavyWeightProcess = null;
2698 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2699 }
2700 }
2701
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002702 public void crashApplication(int uid, int initialPid, String packageName,
2703 String message) {
2704 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2705 != PackageManager.PERMISSION_GRANTED) {
2706 String msg = "Permission Denial: crashApplication() from pid="
2707 + Binder.getCallingPid()
2708 + ", uid=" + Binder.getCallingUid()
2709 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2710 Slog.w(TAG, msg);
2711 throw new SecurityException(msg);
2712 }
2713
2714 synchronized(this) {
2715 ProcessRecord proc = null;
2716
2717 // Figure out which process to kill. We don't trust that initialPid
2718 // still has any relation to current pids, so must scan through the
2719 // list.
2720 synchronized (mPidsSelfLocked) {
2721 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2722 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002723 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002724 continue;
2725 }
2726 if (p.pid == initialPid) {
2727 proc = p;
2728 break;
2729 }
2730 for (String str : p.pkgList) {
2731 if (str.equals(packageName)) {
2732 proc = p;
2733 }
2734 }
2735 }
2736 }
2737
2738 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002739 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002740 + " initialPid=" + initialPid
2741 + " packageName=" + packageName);
2742 return;
2743 }
2744
2745 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002746 if (proc.pid == Process.myPid()) {
2747 Log.w(TAG, "crashApplication: trying to crash self!");
2748 return;
2749 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002750 long ident = Binder.clearCallingIdentity();
2751 try {
2752 proc.thread.scheduleCrash(message);
2753 } catch (RemoteException e) {
2754 }
2755 Binder.restoreCallingIdentity(ident);
2756 }
2757 }
2758 }
2759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002760 public final void finishSubActivity(IBinder token, String resultWho,
2761 int requestCode) {
2762 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002764 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002765 Binder.restoreCallingIdentity(origId);
2766 }
2767 }
2768
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002769 public boolean finishActivityAffinity(IBinder token) {
2770 synchronized(this) {
2771 final long origId = Binder.clearCallingIdentity();
2772 boolean res = mMainStack.finishActivityAffinityLocked(token);
2773 Binder.restoreCallingIdentity(origId);
2774 return res;
2775 }
2776 }
2777
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002778 public boolean willActivityBeVisible(IBinder token) {
2779 synchronized(this) {
2780 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002781 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2782 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002783 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002784 return true;
2785 }
2786 if (r.fullscreen && !r.finishing) {
2787 return false;
2788 }
2789 }
2790 return true;
2791 }
2792 }
2793
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002794 public void overridePendingTransition(IBinder token, String packageName,
2795 int enterAnim, int exitAnim) {
2796 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002797 ActivityRecord self = mMainStack.isInStackLocked(token);
2798 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002799 return;
2800 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002801
2802 final long origId = Binder.clearCallingIdentity();
2803
2804 if (self.state == ActivityState.RESUMED
2805 || self.state == ActivityState.PAUSING) {
2806 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002807 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002808 }
2809
2810 Binder.restoreCallingIdentity(origId);
2811 }
2812 }
2813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 * Main function for removing an existing process from the activity manager
2816 * as a result of that process going away. Clears out all connections
2817 * to the process.
2818 */
2819 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002820 boolean restarting, boolean allowRestart) {
2821 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002823 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 }
2825
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002826 if (mProfileProc == app) {
2827 clearProfilerLocked();
2828 }
2829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002831 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2832 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2833 mMainStack.mPausingActivity = null;
2834 }
2835 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2836 mMainStack.mLastPausedActivity = null;
2837 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838
2839 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002840 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841
2842 boolean atTop = true;
2843 boolean hasVisibleActivities = false;
2844
2845 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002846 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002847 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 TAG, "Removing app " + app + " from history with " + i + " entries");
2849 while (i > 0) {
2850 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002851 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002852 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2854 if (r.app == app) {
2855 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002856 if (ActivityStack.DEBUG_ADD_REMOVE) {
2857 RuntimeException here = new RuntimeException("here");
2858 here.fillInStackTrace();
2859 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2860 + ": haveState=" + r.haveState
2861 + " stateNotNeeded=" + r.stateNotNeeded
2862 + " finishing=" + r.finishing
2863 + " state=" + r.state, here);
2864 }
2865 if (!r.finishing) {
2866 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002867 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2868 System.identityHashCode(r),
2869 r.task.taskId, r.shortComponentName,
2870 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002871 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002872 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873
2874 } else {
2875 // We have the current state for this activity, so
2876 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002877 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002878 TAG, "Keeping entry, setting app to null");
2879 if (r.visible) {
2880 hasVisibleActivities = true;
2881 }
2882 r.app = null;
2883 r.nowVisible = false;
2884 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002885 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2886 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 r.icicle = null;
2888 }
2889 }
2890
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002891 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 }
2893 atTop = false;
2894 }
2895
2896 app.activities.clear();
2897
2898 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002899 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 + " running instrumentation " + app.instrumentationClass);
2901 Bundle info = new Bundle();
2902 info.putString("shortMsg", "Process crashed.");
2903 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2904 }
2905
2906 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002907 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 // If there was nothing to resume, and we are not already
2909 // restarting this process, but there is a visible activity that
2910 // is hosted by the process... then make sure all visible
2911 // activities are running, taking care of restarting this
2912 // process.
2913 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002914 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 }
2916 }
2917 }
2918 }
2919
2920 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2921 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002923 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2924 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002925 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2926 return i;
2927 }
2928 }
2929 return -1;
2930 }
2931
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002932 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 IApplicationThread thread) {
2934 if (thread == null) {
2935 return null;
2936 }
2937
2938 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002939 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 }
2941
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002942 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 IApplicationThread thread) {
2944
2945 mProcDeaths[0]++;
2946
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002947 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2948 synchronized (stats) {
2949 stats.noteProcessDiedLocked(app.info.uid, pid);
2950 }
2951
Magnus Edlund7bb25812010-02-24 15:45:06 +01002952 // Clean up already done if the process has been re-started.
2953 if (app.pid == pid && app.thread != null &&
2954 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002955 if (!app.killedBackground) {
2956 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2957 + ") has died.");
2958 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002959 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002960 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 TAG, "Dying app: " + app + ", pid: " + pid
2962 + ", thread: " + thread.asBinder());
2963 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002964 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965
2966 if (doLowMem) {
2967 // If there are no longer any background processes running,
2968 // and the app that died was not running instrumentation,
2969 // then tell everyone we are now low on memory.
2970 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002971 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2972 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002973 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 haveBg = true;
2975 break;
2976 }
2977 }
2978
2979 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002980 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002981 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002982 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2983 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002984 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002985 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2986 // The low memory report is overriding any current
2987 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002988 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002989 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002990 rec.lastRequestedGc = 0;
2991 } else {
2992 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002994 rec.reportLowMemory = true;
2995 rec.lastLowMemory = now;
2996 mProcessesToGc.remove(rec);
2997 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002998 }
2999 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003000 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003001 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 }
3003 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003004 } else if (app.pid != pid) {
3005 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003006 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003007 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003008 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003009 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003010 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 + thread.asBinder());
3012 }
3013 }
3014
Dan Egnor42471dd2010-01-07 17:25:22 -08003015 /**
3016 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003017 * @param clearTraces causes the dump file to be erased prior to the new
3018 * traces being written, if true; when false, the new traces will be
3019 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003020 * @param firstPids of dalvik VM processes to dump stack traces for first
3021 * @param lastPids of dalvik VM processes to dump stack traces for last
Dan Egnor42471dd2010-01-07 17:25:22 -08003022 * @return file containing stack traces, or null if no dump file is configured
3023 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003024 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
3025 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003026 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3027 if (tracesPath == null || tracesPath.length() == 0) {
3028 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003030
3031 File tracesFile = new File(tracesPath);
3032 try {
3033 File tracesDir = tracesFile.getParentFile();
3034 if (!tracesDir.exists()) tracesFile.mkdirs();
3035 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3036
Christopher Tate6ee412d2010-05-28 12:01:56 -07003037 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003038 tracesFile.createNewFile();
3039 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3040 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003041 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003042 return null;
3043 }
3044
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003045 dumpStackTraces(tracesPath, firstPids, processStats, lastPids);
3046 return tracesFile;
3047 }
3048
3049 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
3050 ProcessStats processStats, SparseArray<Boolean> lastPids) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003051 // Use a FileObserver to detect when traces finish writing.
3052 // The order of traces is considered important to maintain for legibility.
3053 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3054 public synchronized void onEvent(int event, String path) { notify(); }
3055 };
3056
3057 try {
3058 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003059
3060 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003061 if (firstPids != null) {
3062 try {
3063 int num = firstPids.size();
3064 for (int i = 0; i < num; i++) {
3065 synchronized (observer) {
3066 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3067 observer.wait(200); // Wait for write-close, give up after 200msec
3068 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003069 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003070 } catch (InterruptedException e) {
3071 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003072 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003073 }
3074
3075 // Next measure CPU usage.
3076 if (processStats != null) {
3077 processStats.init();
3078 System.gc();
3079 processStats.update();
3080 try {
3081 synchronized (processStats) {
3082 processStats.wait(500); // measure over 1/2 second.
3083 }
3084 } catch (InterruptedException e) {
3085 }
3086 processStats.update();
3087
3088 // We'll take the stack crawls of just the top apps using CPU.
3089 final int N = processStats.countWorkingStats();
3090 int numProcs = 0;
3091 for (int i=0; i<N && numProcs<5; i++) {
3092 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3093 if (lastPids.indexOfKey(stats.pid) >= 0) {
3094 numProcs++;
3095 try {
3096 synchronized (observer) {
3097 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3098 observer.wait(200); // Wait for write-close, give up after 200msec
3099 }
3100 } catch (InterruptedException e) {
3101 Log.wtf(TAG, e);
3102 }
3103
3104 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003105 }
3106 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003107
Dan Egnor42471dd2010-01-07 17:25:22 -08003108 } finally {
3109 observer.stopWatching();
3110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 }
3112
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003113 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003114 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003115 return;
3116 }
3117 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3118 if (tracesPath == null || tracesPath.length() == 0) {
3119 return;
3120 }
3121
3122 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3123 StrictMode.allowThreadDiskWrites();
3124 try {
3125 final File tracesFile = new File(tracesPath);
3126 final File tracesDir = tracesFile.getParentFile();
3127 final File tracesTmp = new File(tracesDir, "__tmp__");
3128 try {
3129 if (!tracesDir.exists()) tracesFile.mkdirs();
3130 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3131
3132 if (tracesFile.exists()) {
3133 tracesTmp.delete();
3134 tracesFile.renameTo(tracesTmp);
3135 }
3136 StringBuilder sb = new StringBuilder();
3137 Time tobj = new Time();
3138 tobj.set(System.currentTimeMillis());
3139 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3140 sb.append(": ");
3141 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3142 sb.append(" since ");
3143 sb.append(msg);
3144 FileOutputStream fos = new FileOutputStream(tracesFile);
3145 fos.write(sb.toString().getBytes());
3146 if (app == null) {
3147 fos.write("\n*** No application process!".getBytes());
3148 }
3149 fos.close();
3150 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3151 } catch (IOException e) {
3152 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3153 return;
3154 }
3155
3156 if (app != null) {
3157 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3158 firstPids.add(app.pid);
3159 dumpStackTraces(tracesPath, firstPids, null, null);
3160 }
3161
3162 File lastTracesFile = null;
3163 File curTracesFile = null;
3164 for (int i=9; i>=0; i--) {
3165 String name = String.format("slow%02d.txt", i);
3166 curTracesFile = new File(tracesDir, name);
3167 if (curTracesFile.exists()) {
3168 if (lastTracesFile != null) {
3169 curTracesFile.renameTo(lastTracesFile);
3170 } else {
3171 curTracesFile.delete();
3172 }
3173 }
3174 lastTracesFile = curTracesFile;
3175 }
3176 tracesFile.renameTo(curTracesFile);
3177 if (tracesTmp.exists()) {
3178 tracesTmp.renameTo(tracesFile);
3179 }
3180 } finally {
3181 StrictMode.setThreadPolicy(oldPolicy);
3182 }
3183 }
3184
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003185 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3186 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003187 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3188 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3189
Dianne Hackborn287952c2010-09-22 22:34:31 -07003190 if (mController != null) {
3191 try {
3192 // 0 == continue, -1 = kill process immediately
3193 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3194 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3195 } catch (RemoteException e) {
3196 mController = null;
3197 }
3198 }
3199
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003200 long anrTime = SystemClock.uptimeMillis();
3201 if (MONITOR_CPU_USAGE) {
3202 updateCpuStatsNow();
3203 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003204
3205 synchronized (this) {
3206 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3207 if (mShuttingDown) {
3208 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3209 return;
3210 } else if (app.notResponding) {
3211 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3212 return;
3213 } else if (app.crashing) {
3214 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3215 return;
3216 }
3217
3218 // In case we come through here for the same app before completing
3219 // this one, mark as anring now so we will bail out.
3220 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003221
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003222 // Log the ANR to the event log.
3223 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3224 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003225
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003226 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003227 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003228
3229 int parentPid = app.pid;
3230 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003231 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003232
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003233 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003234
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003235 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3236 ProcessRecord r = mLruProcesses.get(i);
3237 if (r != null && r.thread != null) {
3238 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003239 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3240 if (r.persistent) {
3241 firstPids.add(pid);
3242 } else {
3243 lastPids.put(pid, Boolean.TRUE);
3244 }
3245 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 }
3248 }
3249
Dan Egnor42471dd2010-01-07 17:25:22 -08003250 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003251 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003252 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003253 info.append("ANR in ").append(app.processName);
3254 if (activity != null && activity.shortComponentName != null) {
3255 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003256 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003257 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003259 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003261 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003262 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264
Dianne Hackborn287952c2010-09-22 22:34:31 -07003265 final ProcessStats processStats = new ProcessStats(true);
3266
3267 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids);
3268
Dan Egnor42471dd2010-01-07 17:25:22 -08003269 String cpuInfo = null;
3270 if (MONITOR_CPU_USAGE) {
3271 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003272 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003273 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003274 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003275 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003276 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 }
3278
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003279 info.append(processStats.printCurrentState(anrTime));
3280
Joe Onorato8a9b2202010-02-26 18:56:32 -08003281 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003282 if (tracesFile == null) {
3283 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3284 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3285 }
3286
Jeff Sharkeya353d262011-10-28 11:12:06 -07003287 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3288 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003289
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003290 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003292 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3293 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003295 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3296 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 }
3298 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003299 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 }
3301 }
3302
Dan Egnor42471dd2010-01-07 17:25:22 -08003303 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3304 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3305 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003306
3307 synchronized (this) {
3308 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003309 Slog.w(TAG, "Killing " + app + ": background ANR");
3310 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3311 app.processName, app.setAdj, "background ANR");
3312 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003313 return;
3314 }
3315
3316 // Set the app's notResponding state, and look up the errorReportReceiver
3317 makeAppNotRespondingLocked(app,
3318 activity != null ? activity.shortComponentName : null,
3319 annotation != null ? "ANR " + annotation : "ANR",
3320 info.toString());
3321
3322 // Bring up the infamous App Not Responding dialog
3323 Message msg = Message.obtain();
3324 HashMap map = new HashMap();
3325 msg.what = SHOW_NOT_RESPONDING_MSG;
3326 msg.obj = map;
3327 map.put("app", app);
3328 if (activity != null) {
3329 map.put("activity", activity);
3330 }
3331
3332 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 }
3335
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003336 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3337 if (!mLaunchWarningShown) {
3338 mLaunchWarningShown = true;
3339 mHandler.post(new Runnable() {
3340 @Override
3341 public void run() {
3342 synchronized (ActivityManagerService.this) {
3343 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3344 d.show();
3345 mHandler.postDelayed(new Runnable() {
3346 @Override
3347 public void run() {
3348 synchronized (ActivityManagerService.this) {
3349 d.dismiss();
3350 mLaunchWarningShown = false;
3351 }
3352 }
3353 }, 4000);
3354 }
3355 }
3356 });
3357 }
3358 }
3359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003361 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003362 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 int uid = Binder.getCallingUid();
3364 int pid = Binder.getCallingPid();
3365 long callingId = Binder.clearCallingIdentity();
3366 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003367 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 int pkgUid = -1;
3369 synchronized(this) {
3370 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003371 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003372 } catch (RemoteException e) {
3373 }
3374 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003375 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 return false;
3377 }
3378 if (uid == pkgUid || checkComponentPermission(
3379 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003380 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003382 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 } else {
3384 throw new SecurityException(pid+" does not have permission:"+
3385 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3386 "for process:"+packageName);
3387 }
3388 }
3389
3390 try {
3391 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003392 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3394 Uri.fromParts("package", packageName, null));
3395 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003396 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003397 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 } catch (RemoteException e) {
3399 }
3400 } finally {
3401 Binder.restoreCallingIdentity(callingId);
3402 }
3403 return true;
3404 }
3405
Dianne Hackborn03abb812010-01-04 18:43:19 -08003406 public void killBackgroundProcesses(final String packageName) {
3407 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3408 != PackageManager.PERMISSION_GRANTED &&
3409 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3410 != PackageManager.PERMISSION_GRANTED) {
3411 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 + Binder.getCallingPid()
3413 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003414 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003415 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 throw new SecurityException(msg);
3417 }
3418
Amith Yamasani483f3b02012-03-13 16:08:00 -07003419 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 long callingId = Binder.clearCallingIdentity();
3421 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003422 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003423 int pkgUid = -1;
3424 synchronized(this) {
3425 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003426 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 } catch (RemoteException e) {
3428 }
3429 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003430 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 return;
3432 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003433 killPackageProcessesLocked(packageName, pkgUid,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003434 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3435 }
3436 } finally {
3437 Binder.restoreCallingIdentity(callingId);
3438 }
3439 }
3440
3441 public void killAllBackgroundProcesses() {
3442 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3443 != PackageManager.PERMISSION_GRANTED) {
3444 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3445 + Binder.getCallingPid()
3446 + ", uid=" + Binder.getCallingUid()
3447 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3448 Slog.w(TAG, msg);
3449 throw new SecurityException(msg);
3450 }
3451
3452 long callingId = Binder.clearCallingIdentity();
3453 try {
3454 synchronized(this) {
3455 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3456 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3457 final int NA = apps.size();
3458 for (int ia=0; ia<NA; ia++) {
3459 ProcessRecord app = apps.valueAt(ia);
3460 if (app.persistent) {
3461 // we don't kill persistent processes
3462 continue;
3463 }
3464 if (app.removed) {
3465 procs.add(app);
3466 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3467 app.removed = true;
3468 procs.add(app);
3469 }
3470 }
3471 }
3472
3473 int N = procs.size();
3474 for (int i=0; i<N; i++) {
3475 removeProcessLocked(procs.get(i), false, true, "kill all background");
3476 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003477 }
3478 } finally {
3479 Binder.restoreCallingIdentity(callingId);
3480 }
3481 }
3482
3483 public void forceStopPackage(final String packageName) {
3484 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3485 != PackageManager.PERMISSION_GRANTED) {
3486 String msg = "Permission Denial: forceStopPackage() from pid="
3487 + Binder.getCallingPid()
3488 + ", uid=" + Binder.getCallingUid()
3489 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003490 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003491 throw new SecurityException(msg);
3492 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07003493 final int userId = UserId.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003494 long callingId = Binder.clearCallingIdentity();
3495 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003496 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003497 int pkgUid = -1;
3498 synchronized(this) {
3499 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003500 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003501 } catch (RemoteException e) {
3502 }
3503 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003504 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003505 return;
3506 }
3507 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003508 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003509 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003510 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003511 } catch (IllegalArgumentException e) {
3512 Slog.w(TAG, "Failed trying to unstop package "
3513 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003515 }
3516 } finally {
3517 Binder.restoreCallingIdentity(callingId);
3518 }
3519 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003520
3521 /*
3522 * The pkg name and uid have to be specified.
3523 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3524 */
3525 public void killApplicationWithUid(String pkg, int uid) {
3526 if (pkg == null) {
3527 return;
3528 }
3529 // Make sure the uid is valid.
3530 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003531 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003532 return;
3533 }
3534 int callerUid = Binder.getCallingUid();
3535 // Only the system server can kill an application
3536 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003537 // Post an aysnc message to kill the application
3538 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3539 msg.arg1 = uid;
3540 msg.arg2 = 0;
3541 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003542 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003543 } else {
3544 throw new SecurityException(callerUid + " cannot kill pkg: " +
3545 pkg);
3546 }
3547 }
3548
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003549 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003550 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003551
3552 final int uid = Binder.getCallingUid();
3553 final long origId = Binder.clearCallingIdentity();
3554 synchronized (this) {
3555 closeSystemDialogsLocked(uid, reason);
3556 }
3557 Binder.restoreCallingIdentity(origId);
3558 }
3559
3560 void closeSystemDialogsLocked(int callingUid, String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003561 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003562 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003563 if (reason != null) {
3564 intent.putExtra("reason", reason);
3565 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003566 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003567
Dianne Hackborne302a162012-05-15 14:58:32 -07003568 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3569 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborna3a041d2012-05-31 16:18:21 -07003570 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0
3571 && (r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLOSE_SYSTEM_DIALOGS) == 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003572 r.stack.finishActivityLocked(r, i,
3573 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003574 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003575 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003576
3577 broadcastIntentLocked(null, null, intent, null,
3578 null, 0, null, null, null, false, false, -1,
3579 callingUid, 0 /* TODO: Verify */);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003580 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003581
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003582 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003583 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003584 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003585 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3586 for (int i=pids.length-1; i>=0; i--) {
3587 infos[i] = new Debug.MemoryInfo();
3588 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003589 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003590 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003591 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003592
Dianne Hackbornb437e092011-08-05 17:50:29 -07003593 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003594 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003595 long[] pss = new long[pids.length];
3596 for (int i=pids.length-1; i>=0; i--) {
3597 pss[i] = Debug.getPss(pids[i]);
3598 }
3599 return pss;
3600 }
3601
Christopher Tate5e1ab332009-09-01 20:32:49 -07003602 public void killApplicationProcess(String processName, int uid) {
3603 if (processName == null) {
3604 return;
3605 }
3606
3607 int callerUid = Binder.getCallingUid();
3608 // Only the system server can kill an application
3609 if (callerUid == Process.SYSTEM_UID) {
3610 synchronized (this) {
3611 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003612 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003613 try {
3614 app.thread.scheduleSuicide();
3615 } catch (RemoteException e) {
3616 // If the other end already died, then our work here is done.
3617 }
3618 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003619 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003620 + processName + " / " + uid);
3621 }
3622 }
3623 } else {
3624 throw new SecurityException(callerUid + " cannot kill app process: " +
3625 processName);
3626 }
3627 }
3628
Dianne Hackborn03abb812010-01-04 18:43:19 -08003629 private void forceStopPackageLocked(final String packageName, int uid) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003630 forceStopPackageLocked(packageName, uid, false, false, true, false, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3632 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003633 if (!mProcessesReady) {
3634 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 intent.putExtra(Intent.EXTRA_UID, uid);
3637 broadcastIntentLocked(null, null, intent,
3638 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003639 false, false,
3640 MY_PID, Process.SYSTEM_UID, UserId.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 }
3642
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003643 private final boolean killPackageProcessesLocked(String packageName, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003644 int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003645 boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003646 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647
Dianne Hackborn03abb812010-01-04 18:43:19 -08003648 // Remove all processes this package may have touched: all with the
3649 // same UID (except for the system or root user), and all whose name
3650 // matches the package name.
3651 final String procNamePrefix = packageName + ":";
3652 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3653 final int NA = apps.size();
3654 for (int ia=0; ia<NA; ia++) {
3655 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003656 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003657 // we don't kill persistent processes
3658 continue;
3659 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003660 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003661 if (doit) {
3662 procs.add(app);
3663 }
Amith Yamasani13593602012-03-22 16:16:17 -07003664 // If uid is specified and the uid and process name match
3665 // Or, the uid is not specified and the process name matches
3666 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003667 || ((app.processName.equals(packageName)
3668 || app.processName.startsWith(procNamePrefix))
3669 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003670 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003671 if (!doit) {
3672 return true;
3673 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003674 app.removed = true;
3675 procs.add(app);
3676 }
3677 }
3678 }
3679 }
3680
3681 int N = procs.size();
3682 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003683 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003684 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003685 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003686 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003687
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003688 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003689 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003690 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003691 int i;
3692 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 if (uid < 0) {
3695 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003696 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 } catch (RemoteException e) {
3698 }
3699 }
3700
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003701 if (doit) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003702 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003703
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003704 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3705 while (badApps.hasNext()) {
3706 SparseArray<Long> ba = badApps.next();
3707 if (ba.get(uid) != null) {
3708 badApps.remove();
3709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003710 }
3711 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003712
3713 boolean didSomething = killPackageProcessesLocked(name, uid, -100,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003714 callerWillRestart, false, doit, evenPersistent, "force stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003716 TaskRecord lastTask = null;
3717 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003718 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003719 final boolean samePackage = r.packageName.equals(name);
Amith Yamasani13593602012-03-22 16:16:17 -07003720 if (r.userId == userId
3721 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003722 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003723 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003724 if (r.finishing) {
3725 // If this activity is just finishing, then it is not
3726 // interesting as far as something to stop.
3727 continue;
3728 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003729 return true;
3730 }
3731 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003732 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003733 if (samePackage) {
3734 if (r.app != null) {
3735 r.app.removed = true;
3736 }
3737 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003739 lastTask = r.task;
3740 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003741 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003742 i--;
3743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 }
3745 }
3746
3747 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Amith Yamasani742a6712011-05-04 14:49:28 -07003748 for (ServiceRecord service : mServiceMap.getAllServices(userId)) {
Christopher Tate064d8422011-07-26 15:38:07 -07003749 if (service.packageName.equals(name)
Christopher Tate3dacd842011-08-19 14:56:15 -07003750 && (service.app == null || evenPersistent || !service.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003751 if (!doit) {
3752 return true;
3753 }
3754 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003755 Slog.i(TAG, " Force stopping service " + service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 if (service.app != null) {
3757 service.app.removed = true;
3758 }
3759 service.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003760 service.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003761 services.add(service);
3762 }
3763 }
3764
3765 N = services.size();
3766 for (i=0; i<N; i++) {
3767 bringDownServiceLocked(services.get(i), true);
3768 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003769
3770 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003771 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003772 if (provider.info.packageName.equals(name)
3773 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3774 if (!doit) {
3775 return true;
3776 }
3777 didSomething = true;
3778 providers.add(provider);
3779 }
3780 }
3781
3782 N = providers.size();
3783 for (i=0; i<N; i++) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003784 removeDyingProviderLocked(null, providers.get(i), true);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003785 }
3786
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003787 if (doit) {
3788 if (purgeCache) {
3789 AttributeCache ac = AttributeCache.instance();
3790 if (ac != null) {
3791 ac.removePackage(name);
3792 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003793 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003794 if (mBooted) {
3795 mMainStack.resumeTopActivityLocked(null);
3796 mMainStack.scheduleIdleLocked();
3797 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003798 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003799
3800 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 }
3802
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003803 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003804 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003806 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003807 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003808 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 + "/" + uid + ")");
3810
3811 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003812 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003813 if (mHeavyWeightProcess == app) {
3814 mHeavyWeightProcess = null;
3815 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 boolean needRestart = false;
3818 if (app.pid > 0 && app.pid != MY_PID) {
3819 int pid = app.pid;
3820 synchronized (mPidsSelfLocked) {
3821 mPidsSelfLocked.remove(pid);
3822 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3823 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003824 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003825 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003826 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003827 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003829 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003830 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003831 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 } else {
3833 needRestart = true;
3834 }
3835 }
3836 } else {
3837 mRemovedProcesses.add(app);
3838 }
3839
3840 return needRestart;
3841 }
3842
3843 private final void processStartTimedOutLocked(ProcessRecord app) {
3844 final int pid = app.pid;
3845 boolean gone = false;
3846 synchronized (mPidsSelfLocked) {
3847 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3848 if (knownApp != null && knownApp.thread == null) {
3849 mPidsSelfLocked.remove(pid);
3850 gone = true;
3851 }
3852 }
3853
3854 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003855 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003856 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003857 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003858 mProcessNames.remove(app.processName, app.uid);
3859 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003860 if (mHeavyWeightProcess == app) {
3861 mHeavyWeightProcess = null;
3862 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3863 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003864 // Take care of any launching providers waiting for this process.
3865 checkAppInLaunchingProvidersLocked(app, true);
3866 // Take care of any services that are waiting for the process.
3867 for (int i=0; i<mPendingServices.size(); i++) {
3868 ServiceRecord sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003869 if ((app.uid == sr.appInfo.uid
3870 && app.processName.equals(sr.processName))
3871 || sr.isolatedProc == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003872 Slog.w(TAG, "Forcing bringing down service: " + sr);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003873 sr.isolatedProc = null;
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003874 mPendingServices.remove(i);
3875 i--;
3876 bringDownServiceLocked(sr, true);
3877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003879 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3880 app.processName, app.setAdj, "start timeout");
3881 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003882 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003883 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003884 try {
3885 IBackupManager bm = IBackupManager.Stub.asInterface(
3886 ServiceManager.getService(Context.BACKUP_SERVICE));
3887 bm.agentDisconnected(app.info.packageName);
3888 } catch (RemoteException e) {
3889 // Can't happen; the backup manager is local
3890 }
3891 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003892 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003893 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003894 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003897 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 }
3899 }
3900
3901 private final boolean attachApplicationLocked(IApplicationThread thread,
3902 int pid) {
3903
3904 // Find the application record that is being attached... either via
3905 // the pid if we are running in multiple processes, or just pull the
3906 // next app record if we are emulating process with anonymous threads.
3907 ProcessRecord app;
3908 if (pid != MY_PID && pid >= 0) {
3909 synchronized (mPidsSelfLocked) {
3910 app = mPidsSelfLocked.get(pid);
3911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 } else {
3913 app = null;
3914 }
3915
3916 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003917 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003919 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003921 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 } else {
3923 try {
3924 thread.scheduleExit();
3925 } catch (Exception e) {
3926 // Ignore exceptions.
3927 }
3928 }
3929 return false;
3930 }
3931
3932 // If this application record is still attached to a previous
3933 // process, clean it up now.
3934 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003935 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 }
3937
3938 // Tell the process all about itself.
3939
Joe Onorato8a9b2202010-02-26 18:56:32 -08003940 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 TAG, "Binding process pid " + pid + " to record " + app);
3942
3943 String processName = app.processName;
3944 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003945 AppDeathRecipient adr = new AppDeathRecipient(
3946 app, pid, thread);
3947 thread.asBinder().linkToDeath(adr, 0);
3948 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 } catch (RemoteException e) {
3950 app.resetPackageList();
3951 startProcessLocked(app, "link fail", processName);
3952 return false;
3953 }
3954
Doug Zongker2bec3d42009-12-04 12:52:44 -08003955 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956
3957 app.thread = thread;
3958 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08003959 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
3960 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 app.forcingToForeground = null;
3962 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07003963 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 app.debugging = false;
3965
3966 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3967
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003968 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003969 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003971 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003972 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07003973 }
3974
Joe Onorato8a9b2202010-02-26 18:56:32 -08003975 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003976 TAG, "New app record " + app
3977 + " thread=" + thread.asBinder() + " pid=" + pid);
3978 try {
3979 int testMode = IApplicationThread.DEBUG_OFF;
3980 if (mDebugApp != null && mDebugApp.equals(processName)) {
3981 testMode = mWaitForDebugger
3982 ? IApplicationThread.DEBUG_WAIT
3983 : IApplicationThread.DEBUG_ON;
3984 app.debugging = true;
3985 if (mDebugTransient) {
3986 mDebugApp = mOrigDebugApp;
3987 mWaitForDebugger = mOrigWaitForDebugger;
3988 }
3989 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003990 String profileFile = app.instrumentationProfileFile;
3991 ParcelFileDescriptor profileFd = null;
3992 boolean profileAutoStop = false;
3993 if (mProfileApp != null && mProfileApp.equals(processName)) {
3994 mProfileProc = app;
3995 profileFile = mProfileFile;
3996 profileFd = mProfileFd;
3997 profileAutoStop = mAutoStopProfiler;
3998 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08003999 boolean enableOpenGlTrace = false;
4000 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4001 enableOpenGlTrace = true;
4002 mOpenGlTraceApp = null;
4003 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004004
Christopher Tate181fafa2009-05-14 11:12:14 -07004005 // If the app is being launched for restore or full backup, set it up specially
4006 boolean isRestrictedBackupMode = false;
4007 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4008 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004009 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004010 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4011 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004012
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004013 ensurePackageDexOpt(app.instrumentationInfo != null
4014 ? app.instrumentationInfo.packageName
4015 : app.info.packageName);
4016 if (app.instrumentationClass != null) {
4017 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004018 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004019 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004020 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004021 ApplicationInfo appInfo = app.instrumentationInfo != null
4022 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004023 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004024 if (profileFd != null) {
4025 profileFd = profileFd.dup();
4026 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004027 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004028 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004029 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4030 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004031 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004032 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004033 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004034 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 } catch (Exception e) {
4036 // todo: Yikes! What should we do? For now we will try to
4037 // start another process, but that could easily get us in
4038 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004039 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040
4041 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004042 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 startProcessLocked(app, "bind fail", processName);
4044 return false;
4045 }
4046
4047 // Remove this record from the list of starting applications.
4048 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004049 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4050 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 mProcessesOnHold.remove(app);
4052
4053 boolean badApp = false;
4054 boolean didSomething = false;
4055
4056 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004057 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004058 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004059 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 && processName.equals(hr.processName)) {
4061 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004062 if (mHeadless) {
4063 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4064 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004065 didSomething = true;
4066 }
4067 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004068 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004069 + hr.intent.getComponent().flattenToShortString(), e);
4070 badApp = true;
4071 }
4072 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004073 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 }
4075 }
4076
4077 // Find any services that should be running in this process...
4078 if (!badApp && mPendingServices.size() > 0) {
4079 ServiceRecord sr = null;
4080 try {
4081 for (int i=0; i<mPendingServices.size(); i++) {
4082 sr = mPendingServices.get(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004083 if (app != sr.isolatedProc && (app.uid != sr.appInfo.uid
4084 || !processName.equals(sr.processName))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 continue;
4086 }
4087
4088 mPendingServices.remove(i);
4089 i--;
4090 realStartServiceLocked(sr, app);
4091 didSomething = true;
4092 }
4093 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004094 Slog.w(TAG, "Exception in new application when starting service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 + sr.shortName, e);
4096 badApp = true;
4097 }
4098 }
4099
Christopher Tatef46723b2012-01-26 14:19:24 -08004100 // Check if a next-broadcast receiver is in this process...
4101 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004103 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004105 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 }
4108 }
4109
Christopher Tate181fafa2009-05-14 11:12:14 -07004110 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004111 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004112 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004113 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004114 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004115 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4116 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4117 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004118 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004119 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004120 e.printStackTrace();
4121 }
4122 }
4123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 if (badApp) {
4125 // todo: Also need to kill application to deal with all
4126 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004127 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 return false;
4129 }
4130
4131 if (!didSomething) {
4132 updateOomAdjLocked();
4133 }
4134
4135 return true;
4136 }
4137
4138 public final void attachApplication(IApplicationThread thread) {
4139 synchronized (this) {
4140 int callingPid = Binder.getCallingPid();
4141 final long origId = Binder.clearCallingIdentity();
4142 attachApplicationLocked(thread, callingPid);
4143 Binder.restoreCallingIdentity(origId);
4144 }
4145 }
4146
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004147 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004149 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4150 if (stopProfiling) {
4151 synchronized (this) {
4152 if (mProfileProc == r.app) {
4153 if (mProfileFd != null) {
4154 try {
4155 mProfileFd.close();
4156 } catch (IOException e) {
4157 }
4158 clearProfilerLocked();
4159 }
4160 }
4161 }
4162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004163 Binder.restoreCallingIdentity(origId);
4164 }
4165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004167 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004168 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004170
4171 synchronized (this) {
4172 updateEventDispatchingLocked();
4173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 }
4175
Dianne Hackborn661cd522011-08-22 00:26:20 -07004176 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004177 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004178 mWindowManager.showBootMessage(msg, always);
4179 }
4180
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004181 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004182 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004183 final long token = Binder.clearCallingIdentity();
4184 try {
4185 synchronized (this) {
4186 if (mLockScreenShown) {
4187 mLockScreenShown = false;
4188 comeOutOfSleepIfNeededLocked();
4189 }
4190 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004191 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004192 } finally {
4193 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004194 }
4195 }
4196
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004197 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004198 IntentFilter pkgFilter = new IntentFilter();
4199 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4200 pkgFilter.addDataScheme("package");
4201 mContext.registerReceiver(new BroadcastReceiver() {
4202 @Override
4203 public void onReceive(Context context, Intent intent) {
4204 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4205 if (pkgs != null) {
4206 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004207 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004208 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4209 setResultCode(Activity.RESULT_OK);
4210 return;
4211 }
4212 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004213 }
4214 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004215 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004216 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004217
4218 IntentFilter userFilter = new IntentFilter();
4219 userFilter.addAction(Intent.ACTION_USER_REMOVED);
4220 mContext.registerReceiver(new BroadcastReceiver() {
4221 @Override
4222 public void onReceive(Context context, Intent intent) {
4223 onUserRemoved(intent);
4224 }
4225 }, userFilter);
4226
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004227 synchronized (this) {
4228 // Ensure that any processes we had put on hold are now started
4229 // up.
4230 final int NP = mProcessesOnHold.size();
4231 if (NP > 0) {
4232 ArrayList<ProcessRecord> procs =
4233 new ArrayList<ProcessRecord>(mProcessesOnHold);
4234 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004235 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4236 + procs.get(ip));
4237 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004238 }
4239 }
4240
4241 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004242 // Start looking for apps that are abusing wake locks.
4243 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004244 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004245 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004246 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004247 SystemProperties.set("dev.bootcomplete", "1");
Amith Yamasani742a6712011-05-04 14:49:28 -07004248 /* TODO: Send this to all users that are to be logged in on startup */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004249 broadcastIntentLocked(null, null,
4250 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4251 null, null, 0, null, null,
4252 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Amith Yamasani742a6712011-05-04 14:49:28 -07004253 false, false, MY_PID, Process.SYSTEM_UID, Binder.getOrigCallingUser());
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004254 }
4255 }
4256 }
4257
4258 final void ensureBootCompleted() {
4259 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004260 boolean enableScreen;
4261 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004262 booting = mBooting;
4263 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004264 enableScreen = !mBooted;
4265 mBooted = true;
4266 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004267
4268 if (booting) {
4269 finishBooting();
4270 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004271
4272 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004273 enableScreenAfterBoot();
4274 }
4275 }
4276
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004277 public final void activityPaused(IBinder token) {
4278 final long origId = Binder.clearCallingIdentity();
4279 mMainStack.activityPaused(token, false);
4280 Binder.restoreCallingIdentity(origId);
4281 }
4282
4283 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4284 CharSequence description) {
4285 if (localLOGV) Slog.v(
4286 TAG, "Activity stopped: token=" + token);
4287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 // Refuse possible leaked file descriptors
4289 if (icicle != null && icicle.hasFileDescriptors()) {
4290 throw new IllegalArgumentException("File descriptors passed in Bundle");
4291 }
4292
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004293 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294
4295 final long origId = Binder.clearCallingIdentity();
4296
4297 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004298 r = mMainStack.isInStackLocked(token);
4299 if (r != null) {
4300 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 }
4302 }
4303
4304 if (r != null) {
4305 sendPendingThumbnail(r, null, null, null, false);
4306 }
4307
4308 trimApplications();
4309
4310 Binder.restoreCallingIdentity(origId);
4311 }
4312
4313 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004314 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004315 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 }
4317
4318 public String getCallingPackage(IBinder token) {
4319 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004320 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004321 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 }
4323 }
4324
4325 public ComponentName getCallingActivity(IBinder token) {
4326 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004327 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328 return r != null ? r.intent.getComponent() : null;
4329 }
4330 }
4331
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004332 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004333 ActivityRecord r = mMainStack.isInStackLocked(token);
4334 if (r == null) {
4335 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004337 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004338 }
4339
4340 public ComponentName getActivityClassForToken(IBinder token) {
4341 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004342 ActivityRecord r = mMainStack.isInStackLocked(token);
4343 if (r == null) {
4344 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004346 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 }
4348 }
4349
4350 public String getPackageForToken(IBinder token) {
4351 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004352 ActivityRecord r = mMainStack.isInStackLocked(token);
4353 if (r == null) {
4354 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004355 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004356 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004357 }
4358 }
4359
4360 public IIntentSender getIntentSender(int type,
4361 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004362 int requestCode, Intent[] intents, String[] resolvedTypes,
4363 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004364 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004366 if (intents != null) {
4367 if (intents.length < 1) {
4368 throw new IllegalArgumentException("Intents array length must be >= 1");
4369 }
4370 for (int i=0; i<intents.length; i++) {
4371 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004372 if (intent != null) {
4373 if (intent.hasFileDescriptors()) {
4374 throw new IllegalArgumentException("File descriptors passed in Intent");
4375 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004376 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004377 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4378 throw new IllegalArgumentException(
4379 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4380 }
4381 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004382 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004383 }
4384 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004385 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004386 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004387 }
4388 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004389 if (options != null) {
4390 if (options.hasFileDescriptors()) {
4391 throw new IllegalArgumentException("File descriptors passed in options");
4392 }
4393 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004395 synchronized(this) {
4396 int callingUid = Binder.getCallingUid();
4397 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004398 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004399 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004400 .getPackageUid(packageName, UserId.getUserId(callingUid));
4401 if (!UserId.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 String msg = "Permission Denial: getIntentSender() from pid="
4403 + Binder.getCallingPid()
4404 + ", uid=" + Binder.getCallingUid()
4405 + ", (need uid=" + uid + ")"
4406 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004407 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004408 throw new SecurityException(msg);
4409 }
4410 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004411
Amith Yamasani742a6712011-05-04 14:49:28 -07004412 if (DEBUG_MU)
4413 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4414 + Binder.getOrigCallingUid());
4415 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004416 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004418 } catch (RemoteException e) {
4419 throw new SecurityException(e);
4420 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004421 }
4422 }
4423
4424 IIntentSender getIntentSenderLocked(int type,
4425 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004426 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4427 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004428 if (DEBUG_MU)
4429 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004430 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004431 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004432 activity = mMainStack.isInStackLocked(token);
4433 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004434 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004435 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004436 if (activity.finishing) {
4437 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004438 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004439 }
4440
4441 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4442 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4443 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4444 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4445 |PendingIntent.FLAG_UPDATE_CURRENT);
4446
4447 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4448 type, packageName, activity, resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004449 requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004450 WeakReference<PendingIntentRecord> ref;
4451 ref = mIntentSenderRecords.get(key);
4452 PendingIntentRecord rec = ref != null ? ref.get() : null;
4453 if (rec != null) {
4454 if (!cancelCurrent) {
4455 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004456 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004457 rec.key.requestIntent.replaceExtras(intents != null ?
4458 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004459 }
4460 if (intents != null) {
4461 intents[intents.length-1] = rec.key.requestIntent;
4462 rec.key.allIntents = intents;
4463 rec.key.allResolvedTypes = resolvedTypes;
4464 } else {
4465 rec.key.allIntents = null;
4466 rec.key.allResolvedTypes = null;
4467 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 return rec;
4470 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004471 rec.canceled = true;
4472 mIntentSenderRecords.remove(key);
4473 }
4474 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475 return rec;
4476 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004477 rec = new PendingIntentRecord(this, key, callingUid);
4478 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004479 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004480 if (activity.pendingResults == null) {
4481 activity.pendingResults
4482 = new HashSet<WeakReference<PendingIntentRecord>>();
4483 }
4484 activity.pendingResults.add(rec.ref);
4485 }
4486 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 }
4488
4489 public void cancelIntentSender(IIntentSender sender) {
4490 if (!(sender instanceof PendingIntentRecord)) {
4491 return;
4492 }
4493 synchronized(this) {
4494 PendingIntentRecord rec = (PendingIntentRecord)sender;
4495 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004496 int uid = AppGlobals.getPackageManager()
Amith Yamasani483f3b02012-03-13 16:08:00 -07004497 .getPackageUid(rec.key.packageName, UserId.getCallingUserId());
Amith Yamasani04e0d262012-02-14 11:50:53 -08004498 if (!UserId.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499 String msg = "Permission Denial: cancelIntentSender() from pid="
4500 + Binder.getCallingPid()
4501 + ", uid=" + Binder.getCallingUid()
4502 + " is not allowed to cancel packges "
4503 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004504 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 throw new SecurityException(msg);
4506 }
4507 } catch (RemoteException e) {
4508 throw new SecurityException(e);
4509 }
4510 cancelIntentSenderLocked(rec, true);
4511 }
4512 }
4513
4514 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4515 rec.canceled = true;
4516 mIntentSenderRecords.remove(rec.key);
4517 if (cleanActivity && rec.key.activity != null) {
4518 rec.key.activity.pendingResults.remove(rec.ref);
4519 }
4520 }
4521
4522 public String getPackageForIntentSender(IIntentSender pendingResult) {
4523 if (!(pendingResult instanceof PendingIntentRecord)) {
4524 return null;
4525 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004526 try {
4527 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4528 return res.key.packageName;
4529 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 }
4531 return null;
4532 }
4533
Christopher Tatec4a07d12012-04-06 14:19:13 -07004534 public int getUidForIntentSender(IIntentSender sender) {
4535 if (sender instanceof PendingIntentRecord) {
4536 try {
4537 PendingIntentRecord res = (PendingIntentRecord)sender;
4538 return res.uid;
4539 } catch (ClassCastException e) {
4540 }
4541 }
4542 return -1;
4543 }
4544
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004545 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4546 if (!(pendingResult instanceof PendingIntentRecord)) {
4547 return false;
4548 }
4549 try {
4550 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4551 if (res.key.allIntents == null) {
4552 return false;
4553 }
4554 for (int i=0; i<res.key.allIntents.length; i++) {
4555 Intent intent = res.key.allIntents[i];
4556 if (intent.getPackage() != null && intent.getComponent() != null) {
4557 return false;
4558 }
4559 }
4560 return true;
4561 } catch (ClassCastException e) {
4562 }
4563 return false;
4564 }
4565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004566 public void setProcessLimit(int max) {
4567 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4568 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004569 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004570 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004571 mProcessLimitOverride = max;
4572 }
4573 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004574 }
4575
4576 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004577 synchronized (this) {
4578 return mProcessLimitOverride;
4579 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004580 }
4581
4582 void foregroundTokenDied(ForegroundToken token) {
4583 synchronized (ActivityManagerService.this) {
4584 synchronized (mPidsSelfLocked) {
4585 ForegroundToken cur
4586 = mForegroundProcesses.get(token.pid);
4587 if (cur != token) {
4588 return;
4589 }
4590 mForegroundProcesses.remove(token.pid);
4591 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4592 if (pr == null) {
4593 return;
4594 }
4595 pr.forcingToForeground = null;
4596 pr.foregroundServices = false;
4597 }
4598 updateOomAdjLocked();
4599 }
4600 }
4601
4602 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4603 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4604 "setProcessForeground()");
4605 synchronized(this) {
4606 boolean changed = false;
4607
4608 synchronized (mPidsSelfLocked) {
4609 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004610 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004611 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004612 return;
4613 }
4614 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4615 if (oldToken != null) {
4616 oldToken.token.unlinkToDeath(oldToken, 0);
4617 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004618 if (pr != null) {
4619 pr.forcingToForeground = null;
4620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 changed = true;
4622 }
4623 if (isForeground && token != null) {
4624 ForegroundToken newToken = new ForegroundToken() {
4625 public void binderDied() {
4626 foregroundTokenDied(this);
4627 }
4628 };
4629 newToken.pid = pid;
4630 newToken.token = token;
4631 try {
4632 token.linkToDeath(newToken, 0);
4633 mForegroundProcesses.put(pid, newToken);
4634 pr.forcingToForeground = token;
4635 changed = true;
4636 } catch (RemoteException e) {
4637 // If the process died while doing this, we will later
4638 // do the cleanup with the process death link.
4639 }
4640 }
4641 }
4642
4643 if (changed) {
4644 updateOomAdjLocked();
4645 }
4646 }
4647 }
4648
4649 // =========================================================
4650 // PERMISSIONS
4651 // =========================================================
4652
4653 static class PermissionController extends IPermissionController.Stub {
4654 ActivityManagerService mActivityManagerService;
4655 PermissionController(ActivityManagerService activityManagerService) {
4656 mActivityManagerService = activityManagerService;
4657 }
4658
4659 public boolean checkPermission(String permission, int pid, int uid) {
4660 return mActivityManagerService.checkPermission(permission, pid,
4661 uid) == PackageManager.PERMISSION_GRANTED;
4662 }
4663 }
4664
4665 /**
4666 * This can be called with or without the global lock held.
4667 */
4668 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004669 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004670 // We might be performing an operation on behalf of an indirect binder
4671 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4672 // client identity accordingly before proceeding.
4673 Identity tlsIdentity = sCallerIdentity.get();
4674 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004675 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004676 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4677 uid = tlsIdentity.uid;
4678 pid = tlsIdentity.pid;
4679 }
4680
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004681 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 return PackageManager.PERMISSION_GRANTED;
4683 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004684
4685 return ActivityManager.checkComponentPermission(permission, uid,
4686 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004687 }
4688
4689 /**
4690 * As the only public entry point for permissions checking, this method
4691 * can enforce the semantic that requesting a check on a null global
4692 * permission is automatically denied. (Internally a null permission
4693 * string is used when calling {@link #checkComponentPermission} in cases
4694 * when only uid-based security is needed.)
4695 *
4696 * This can be called with or without the global lock held.
4697 */
4698 public int checkPermission(String permission, int pid, int uid) {
4699 if (permission == null) {
4700 return PackageManager.PERMISSION_DENIED;
4701 }
Amith Yamasani742a6712011-05-04 14:49:28 -07004702 return checkComponentPermission(permission, pid, UserId.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004703 }
4704
4705 /**
4706 * Binder IPC calls go through the public entry point.
4707 * This can be called with or without the global lock held.
4708 */
4709 int checkCallingPermission(String permission) {
4710 return checkPermission(permission,
4711 Binder.getCallingPid(),
Amith Yamasani742a6712011-05-04 14:49:28 -07004712 UserId.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004713 }
4714
4715 /**
4716 * This can be called with or without the global lock held.
4717 */
4718 void enforceCallingPermission(String permission, String func) {
4719 if (checkCallingPermission(permission)
4720 == PackageManager.PERMISSION_GRANTED) {
4721 return;
4722 }
4723
4724 String msg = "Permission Denial: " + func + " from pid="
4725 + Binder.getCallingPid()
4726 + ", uid=" + Binder.getCallingUid()
4727 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004728 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004729 throw new SecurityException(msg);
4730 }
4731
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004732 /**
4733 * Determine if UID is holding permissions required to access {@link Uri} in
4734 * the given {@link ProviderInfo}. Final permission checking is always done
4735 * in {@link ContentProvider}.
4736 */
4737 private final boolean checkHoldingPermissionsLocked(
4738 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004739 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4740 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004741
4742 if (pi.applicationInfo.uid == uid) {
4743 return true;
4744 } else if (!pi.exported) {
4745 return false;
4746 }
4747
4748 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4749 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004750 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004751 // check if target holds top-level <provider> permissions
4752 if (!readMet && pi.readPermission != null
4753 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4754 readMet = true;
4755 }
4756 if (!writeMet && pi.writePermission != null
4757 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4758 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004759 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004760
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004761 // track if unprotected read/write is allowed; any denied
4762 // <path-permission> below removes this ability
4763 boolean allowDefaultRead = pi.readPermission == null;
4764 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004765
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004766 // check if target holds any <path-permission> that match uri
4767 final PathPermission[] pps = pi.pathPermissions;
4768 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004769 final String path = uri.getPath();
4770 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004771 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004772 i--;
4773 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004774 if (pp.match(path)) {
4775 if (!readMet) {
4776 final String pprperm = pp.getReadPermission();
4777 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4778 + pprperm + " for " + pp.getPath()
4779 + ": match=" + pp.match(path)
4780 + " check=" + pm.checkUidPermission(pprperm, uid));
4781 if (pprperm != null) {
4782 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4783 readMet = true;
4784 } else {
4785 allowDefaultRead = false;
4786 }
4787 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004788 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004789 if (!writeMet) {
4790 final String ppwperm = pp.getWritePermission();
4791 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4792 + ppwperm + " for " + pp.getPath()
4793 + ": match=" + pp.match(path)
4794 + " check=" + pm.checkUidPermission(ppwperm, uid));
4795 if (ppwperm != null) {
4796 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4797 writeMet = true;
4798 } else {
4799 allowDefaultWrite = false;
4800 }
4801 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004802 }
4803 }
4804 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004805 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004806
4807 // grant unprotected <provider> read/write, if not blocked by
4808 // <path-permission> above
4809 if (allowDefaultRead) readMet = true;
4810 if (allowDefaultWrite) writeMet = true;
4811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 } catch (RemoteException e) {
4813 return false;
4814 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004815
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004816 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004817 }
4818
4819 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4820 int modeFlags) {
4821 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004822 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004823 return true;
4824 }
4825 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4826 if (perms == null) return false;
4827 UriPermission perm = perms.get(uri);
4828 if (perm == null) return false;
4829 return (modeFlags&perm.modeFlags) == modeFlags;
4830 }
4831
4832 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004833 enforceNotIsolatedCaller("checkUriPermission");
4834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004835 // Another redirected-binder-call permissions check as in
4836 // {@link checkComponentPermission}.
4837 Identity tlsIdentity = sCallerIdentity.get();
4838 if (tlsIdentity != null) {
4839 uid = tlsIdentity.uid;
4840 pid = tlsIdentity.pid;
4841 }
4842
Amith Yamasani742a6712011-05-04 14:49:28 -07004843 uid = UserId.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004844 // Our own process gets to do everything.
4845 if (pid == MY_PID) {
4846 return PackageManager.PERMISSION_GRANTED;
4847 }
4848 synchronized(this) {
4849 return checkUriPermissionLocked(uri, uid, modeFlags)
4850 ? PackageManager.PERMISSION_GRANTED
4851 : PackageManager.PERMISSION_DENIED;
4852 }
4853 }
4854
Dianne Hackborn39792d22010-08-19 18:01:52 -07004855 /**
4856 * Check if the targetPkg can be granted permission to access uri by
4857 * the callingUid using the given modeFlags. Throws a security exception
4858 * if callingUid is not allowed to do this. Returns the uid of the target
4859 * if the URI permission grant should be performed; returns -1 if it is not
4860 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004861 * If you already know the uid of the target, you can supply it in
4862 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004863 */
4864 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004865 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004866 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4867 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4868 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004869 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004870 }
4871
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004872 if (targetPkg != null) {
4873 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4874 "Checking grant " + targetPkg + " permission to " + uri);
4875 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004876
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004877 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004878
4879 // If this is not a content: uri, we can't do anything with it.
4880 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004881 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004882 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004883 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 }
4885
4886 String name = uri.getAuthority();
4887 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004888 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
4889 UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004890 if (cpr != null) {
4891 pi = cpr.info;
4892 } else {
4893 try {
4894 pi = pm.resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07004895 PackageManager.GET_URI_PERMISSION_PATTERNS, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004896 } catch (RemoteException ex) {
4897 }
4898 }
4899 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004900 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004901 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004902 }
4903
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004904 int targetUid = lastTargetUid;
4905 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004906 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004907 targetUid = pm.getPackageUid(targetPkg, UserId.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004908 if (targetUid < 0) {
4909 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4910 "Can't grant URI permission no uid for: " + targetPkg);
4911 return -1;
4912 }
4913 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004914 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004916 }
4917
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004918 if (targetUid >= 0) {
4919 // First... does the target actually need this permission?
4920 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4921 // No need to grant the target this permission.
4922 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4923 "Target " + targetPkg + " already has full permission to " + uri);
4924 return -1;
4925 }
4926 } else {
4927 // First... there is no target package, so can anyone access it?
4928 boolean allowed = pi.exported;
4929 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4930 if (pi.readPermission != null) {
4931 allowed = false;
4932 }
4933 }
4934 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4935 if (pi.writePermission != null) {
4936 allowed = false;
4937 }
4938 }
4939 if (allowed) {
4940 return -1;
4941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004942 }
4943
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004944 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004945 if (!pi.grantUriPermissions) {
4946 throw new SecurityException("Provider " + pi.packageName
4947 + "/" + pi.name
4948 + " does not allow granting of Uri permissions (uri "
4949 + uri + ")");
4950 }
4951 if (pi.uriPermissionPatterns != null) {
4952 final int N = pi.uriPermissionPatterns.length;
4953 boolean allowed = false;
4954 for (int i=0; i<N; i++) {
4955 if (pi.uriPermissionPatterns[i] != null
4956 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
4957 allowed = true;
4958 break;
4959 }
4960 }
4961 if (!allowed) {
4962 throw new SecurityException("Provider " + pi.packageName
4963 + "/" + pi.name
4964 + " does not allow granting of permission to path of Uri "
4965 + uri);
4966 }
4967 }
4968
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004969 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004970 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004971 if (callingUid != Process.myUid()) {
4972 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
4973 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
4974 throw new SecurityException("Uid " + callingUid
4975 + " does not have permission to uri " + uri);
4976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004977 }
4978 }
4979
Dianne Hackborn39792d22010-08-19 18:01:52 -07004980 return targetUid;
4981 }
4982
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004983 public int checkGrantUriPermission(int callingUid, String targetPkg,
4984 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004985 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004986 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004987 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004988 }
4989 }
4990
Dianne Hackborn39792d22010-08-19 18:01:52 -07004991 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
4992 Uri uri, int modeFlags, UriPermissionOwner owner) {
4993 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4994 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4995 if (modeFlags == 0) {
4996 return;
4997 }
4998
4999 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005000 // to the uri, and the target doesn't. Let's now give this to
5001 // the target.
5002
Joe Onorato8a9b2202010-02-26 18:56:32 -08005003 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005004 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005006 HashMap<Uri, UriPermission> targetUris
5007 = mGrantedUriPermissions.get(targetUid);
5008 if (targetUris == null) {
5009 targetUris = new HashMap<Uri, UriPermission>();
5010 mGrantedUriPermissions.put(targetUid, targetUris);
5011 }
5012
5013 UriPermission perm = targetUris.get(uri);
5014 if (perm == null) {
5015 perm = new UriPermission(targetUid, uri);
5016 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005017 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005019 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005020 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005021 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005022 } else {
5023 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5024 perm.readOwners.add(owner);
5025 owner.addReadPermission(perm);
5026 }
5027 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5028 perm.writeOwners.add(owner);
5029 owner.addWritePermission(perm);
5030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005031 }
5032 }
5033
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005034 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5035 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005036 if (targetPkg == null) {
5037 throw new NullPointerException("targetPkg");
5038 }
5039
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005040 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005041 if (targetUid < 0) {
5042 return;
5043 }
5044
5045 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5046 }
5047
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005048 static class NeededUriGrants extends ArrayList<Uri> {
5049 final String targetPkg;
5050 final int targetUid;
5051 final int flags;
5052
5053 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5054 targetPkg = _targetPkg;
5055 targetUid = _targetUid;
5056 flags = _flags;
5057 }
5058 }
5059
Dianne Hackborn39792d22010-08-19 18:01:52 -07005060 /**
5061 * Like checkGrantUriPermissionLocked, but takes an Intent.
5062 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005063 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5064 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005065 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005066 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5067 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005068 + " from " + intent + "; flags=0x"
5069 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5070
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005071 if (targetPkg == null) {
5072 throw new NullPointerException("targetPkg");
5073 }
5074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005075 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005076 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005077 }
5078 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005079 ClipData clip = intent.getClipData();
5080 if (data == null && clip == null) {
5081 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005082 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005083 if (data != null) {
5084 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5085 mode, needed != null ? needed.targetUid : -1);
5086 if (target > 0) {
5087 if (needed == null) {
5088 needed = new NeededUriGrants(targetPkg, target, mode);
5089 }
5090 needed.add(data);
5091 }
5092 }
5093 if (clip != null) {
5094 for (int i=0; i<clip.getItemCount(); i++) {
5095 Uri uri = clip.getItemAt(i).getUri();
5096 if (uri != null) {
5097 int target = -1;
5098 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5099 mode, needed != null ? needed.targetUid : -1);
5100 if (target > 0) {
5101 if (needed == null) {
5102 needed = new NeededUriGrants(targetPkg, target, mode);
5103 }
5104 needed.add(uri);
5105 }
5106 } else {
5107 Intent clipIntent = clip.getItemAt(i).getIntent();
5108 if (clipIntent != null) {
5109 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5110 callingUid, targetPkg, clipIntent, mode, needed);
5111 if (newNeeded != null) {
5112 needed = newNeeded;
5113 }
5114 }
5115 }
5116 }
5117 }
5118
5119 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005120 }
5121
5122 /**
5123 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5124 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005125 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5126 UriPermissionOwner owner) {
5127 if (needed != null) {
5128 for (int i=0; i<needed.size(); i++) {
5129 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5130 needed.get(i), needed.flags, owner);
5131 }
5132 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005133 }
5134
5135 void grantUriPermissionFromIntentLocked(int callingUid,
5136 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005137 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005138 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005139 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005140 return;
5141 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005142
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005143 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005144 }
5145
5146 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5147 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005148 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005149 synchronized(this) {
5150 final ProcessRecord r = getRecordForAppLocked(caller);
5151 if (r == null) {
5152 throw new SecurityException("Unable to find app for caller "
5153 + caller
5154 + " when granting permission to uri " + uri);
5155 }
5156 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005157 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005158 }
5159 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005160 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005161 }
5162
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005163 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005164 null);
5165 }
5166 }
5167
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005168 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005169 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5170 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5171 HashMap<Uri, UriPermission> perms
5172 = mGrantedUriPermissions.get(perm.uid);
5173 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005174 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005175 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005176 perms.remove(perm.uri);
5177 if (perms.size() == 0) {
5178 mGrantedUriPermissions.remove(perm.uid);
5179 }
5180 }
5181 }
5182 }
5183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005184 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5185 int modeFlags) {
5186 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5187 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5188 if (modeFlags == 0) {
5189 return;
5190 }
5191
Joe Onorato8a9b2202010-02-26 18:56:32 -08005192 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005193 "Revoking all granted permissions to " + uri);
5194
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005195 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005196
5197 final String authority = uri.getAuthority();
5198 ProviderInfo pi = null;
Amith Yamasani483f3b02012-03-13 16:08:00 -07005199 int userId = UserId.getUserId(callingUid);
5200 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005201 if (cpr != null) {
5202 pi = cpr.info;
5203 } else {
5204 try {
5205 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005206 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005207 } catch (RemoteException ex) {
5208 }
5209 }
5210 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005211 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005212 return;
5213 }
5214
5215 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005216 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217 // Right now, if you are not the original owner of the permission,
5218 // you are not allowed to revoke it.
5219 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5220 throw new SecurityException("Uid " + callingUid
5221 + " does not have permission to uri " + uri);
5222 //}
5223 }
5224
5225 // Go through all of the permissions and remove any that match.
5226 final List<String> SEGMENTS = uri.getPathSegments();
5227 if (SEGMENTS != null) {
5228 final int NS = SEGMENTS.size();
5229 int N = mGrantedUriPermissions.size();
5230 for (int i=0; i<N; i++) {
5231 HashMap<Uri, UriPermission> perms
5232 = mGrantedUriPermissions.valueAt(i);
5233 Iterator<UriPermission> it = perms.values().iterator();
5234 toploop:
5235 while (it.hasNext()) {
5236 UriPermission perm = it.next();
5237 Uri targetUri = perm.uri;
5238 if (!authority.equals(targetUri.getAuthority())) {
5239 continue;
5240 }
5241 List<String> targetSegments = targetUri.getPathSegments();
5242 if (targetSegments == null) {
5243 continue;
5244 }
5245 if (targetSegments.size() < NS) {
5246 continue;
5247 }
5248 for (int j=0; j<NS; j++) {
5249 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5250 continue toploop;
5251 }
5252 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005253 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005254 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005255 perm.clearModes(modeFlags);
5256 if (perm.modeFlags == 0) {
5257 it.remove();
5258 }
5259 }
5260 if (perms.size() == 0) {
5261 mGrantedUriPermissions.remove(
5262 mGrantedUriPermissions.keyAt(i));
5263 N--;
5264 i--;
5265 }
5266 }
5267 }
5268 }
5269
5270 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5271 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005272 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 synchronized(this) {
5274 final ProcessRecord r = getRecordForAppLocked(caller);
5275 if (r == null) {
5276 throw new SecurityException("Unable to find app for caller "
5277 + caller
5278 + " when revoking permission to uri " + uri);
5279 }
5280 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005281 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005282 return;
5283 }
5284
5285 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5286 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5287 if (modeFlags == 0) {
5288 return;
5289 }
5290
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005291 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005292
5293 final String authority = uri.getAuthority();
5294 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005295 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005296 if (cpr != null) {
5297 pi = cpr.info;
5298 } else {
5299 try {
5300 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005301 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005302 } catch (RemoteException ex) {
5303 }
5304 }
5305 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005306 Slog.w(TAG, "No content provider found for permission revoke: "
5307 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005308 return;
5309 }
5310
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005311 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005312 }
5313 }
5314
Dianne Hackborn7e269642010-08-25 19:50:20 -07005315 @Override
5316 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005317 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005318 synchronized(this) {
5319 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5320 return owner.getExternalTokenLocked();
5321 }
5322 }
5323
5324 @Override
5325 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5326 Uri uri, int modeFlags) {
5327 synchronized(this) {
5328 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5329 if (owner == null) {
5330 throw new IllegalArgumentException("Unknown owner: " + token);
5331 }
5332 if (fromUid != Binder.getCallingUid()) {
5333 if (Binder.getCallingUid() != Process.myUid()) {
5334 // Only system code can grant URI permissions on behalf
5335 // of other users.
5336 throw new SecurityException("nice try");
5337 }
5338 }
5339 if (targetPkg == null) {
5340 throw new IllegalArgumentException("null target");
5341 }
5342 if (uri == null) {
5343 throw new IllegalArgumentException("null uri");
5344 }
5345
5346 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5347 }
5348 }
5349
5350 @Override
5351 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5352 synchronized(this) {
5353 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5354 if (owner == null) {
5355 throw new IllegalArgumentException("Unknown owner: " + token);
5356 }
5357
5358 if (uri == null) {
5359 owner.removeUriPermissionsLocked(mode);
5360 } else {
5361 owner.removeUriPermissionLocked(uri, mode);
5362 }
5363 }
5364 }
5365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005366 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5367 synchronized (this) {
5368 ProcessRecord app =
5369 who != null ? getRecordForAppLocked(who) : null;
5370 if (app == null) return;
5371
5372 Message msg = Message.obtain();
5373 msg.what = WAIT_FOR_DEBUGGER_MSG;
5374 msg.obj = app;
5375 msg.arg1 = waiting ? 1 : 0;
5376 mHandler.sendMessage(msg);
5377 }
5378 }
5379
5380 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005381 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5382 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005383 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005384 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005385 outInfo.threshold = homeAppMem;
5386 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5387 outInfo.hiddenAppThreshold = hiddenAppMem;
5388 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005389 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005390 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5391 ProcessList.VISIBLE_APP_ADJ);
5392 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5393 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005394 }
5395
5396 // =========================================================
5397 // TASK MANAGEMENT
5398 // =========================================================
5399
5400 public List getTasks(int maxNum, int flags,
5401 IThumbnailReceiver receiver) {
5402 ArrayList list = new ArrayList();
5403
5404 PendingThumbnailsRecord pending = null;
5405 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005406 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005407
5408 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005409 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005410 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5411 + ", receiver=" + receiver);
5412
5413 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5414 != PackageManager.PERMISSION_GRANTED) {
5415 if (receiver != null) {
5416 // If the caller wants to wait for pending thumbnails,
5417 // it ain't gonna get them.
5418 try {
5419 receiver.finished();
5420 } catch (RemoteException ex) {
5421 }
5422 }
5423 String msg = "Permission Denial: getTasks() from pid="
5424 + Binder.getCallingPid()
5425 + ", uid=" + Binder.getCallingUid()
5426 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005427 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005428 throw new SecurityException(msg);
5429 }
5430
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005431 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005432 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005433 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005434 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 TaskRecord curTask = null;
5436 int numActivities = 0;
5437 int numRunning = 0;
5438 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005439 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005440 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005441 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005442
5443 // Initialize state for next task if needed.
5444 if (top == null ||
5445 (top.state == ActivityState.INITIALIZING
5446 && top.task == r.task)) {
5447 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 curTask = r.task;
5449 numActivities = numRunning = 0;
5450 }
5451
5452 // Add 'r' into the current task.
5453 numActivities++;
5454 if (r.app != null && r.app.thread != null) {
5455 numRunning++;
5456 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457
Joe Onorato8a9b2202010-02-26 18:56:32 -08005458 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459 TAG, r.intent.getComponent().flattenToShortString()
5460 + ": task=" + r.task);
5461
5462 // If the next one is a different task, generate a new
5463 // TaskInfo entry for what we have.
5464 if (next == null || next.task != curTask) {
5465 ActivityManager.RunningTaskInfo ci
5466 = new ActivityManager.RunningTaskInfo();
5467 ci.id = curTask.taskId;
5468 ci.baseActivity = r.intent.getComponent();
5469 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005470 if (top.thumbHolder != null) {
5471 ci.description = top.thumbHolder.lastDescription;
5472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005473 ci.numActivities = numActivities;
5474 ci.numRunning = numRunning;
5475 //System.out.println(
5476 // "#" + maxNum + ": " + " descr=" + ci.description);
5477 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005478 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 TAG, "State=" + top.state + "Idle=" + top.idle
5480 + " app=" + top.app
5481 + " thr=" + (top.app != null ? top.app.thread : null));
5482 if (top.state == ActivityState.RESUMED
5483 || top.state == ActivityState.PAUSING) {
5484 if (top.idle && top.app != null
5485 && top.app.thread != null) {
5486 topRecord = top;
5487 topThumbnail = top.app.thread;
5488 } else {
5489 top.thumbnailNeeded = true;
5490 }
5491 }
5492 if (pending == null) {
5493 pending = new PendingThumbnailsRecord(receiver);
5494 }
5495 pending.pendingRecords.add(top);
5496 }
5497 list.add(ci);
5498 maxNum--;
5499 top = null;
5500 }
5501 }
5502
5503 if (pending != null) {
5504 mPendingThumbnails.add(pending);
5505 }
5506 }
5507
Joe Onorato8a9b2202010-02-26 18:56:32 -08005508 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509
5510 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005511 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005513 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005515 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005516 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 }
5518 }
5519
5520 if (pending == null && receiver != null) {
5521 // In this case all thumbnails were available and the client
5522 // is being asked to be told when the remaining ones come in...
5523 // which is unusually, since the top-most currently running
5524 // activity should never have a canned thumbnail! Oh well.
5525 try {
5526 receiver.finished();
5527 } catch (RemoteException ex) {
5528 }
5529 }
5530
5531 return list;
5532 }
5533
5534 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
5535 int flags) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005536 final int callingUid = Binder.getCallingUid();
5537 // If it's the system uid asking, then use the current user id.
5538 // TODO: Make sure that there aren't any other legitimate calls from the system uid that
5539 // require the entire list.
5540 final int callingUserId = callingUid == Process.SYSTEM_UID
5541 ? mCurrentUserId : UserId.getUserId(callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 synchronized (this) {
5543 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5544 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005545 final boolean detailed = checkCallingPermission(
5546 android.Manifest.permission.GET_DETAILED_TASKS)
5547 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005548
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005549 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551 final int N = mRecentTasks.size();
5552 ArrayList<ActivityManager.RecentTaskInfo> res
5553 = new ArrayList<ActivityManager.RecentTaskInfo>(
5554 maxNum < N ? maxNum : N);
5555 for (int i=0; i<N && maxNum > 0; i++) {
5556 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005557 // Only add calling user's recent tasks
5558 if (tr.userId != callingUserId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005559 // Return the entry if desired by the caller. We always return
5560 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005561 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005562 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5563 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005564
Dianne Hackborn905577f2011-09-07 18:31:28 -07005565 if (i == 0
5566 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 || (tr.intent == null)
5568 || ((tr.intent.getFlags()
5569 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5570 ActivityManager.RecentTaskInfo rti
5571 = new ActivityManager.RecentTaskInfo();
5572 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005573 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 rti.baseIntent = new Intent(
5575 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005576 if (!detailed) {
5577 rti.baseIntent.replaceExtras((Bundle)null);
5578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005580 rti.description = tr.lastDescription;
5581
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005582 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5583 // Check whether this activity is currently available.
5584 try {
5585 if (rti.origActivity != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07005586 if (pm.getActivityInfo(rti.origActivity, 0, callingUserId)
5587 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005588 continue;
5589 }
5590 } else if (rti.baseIntent != null) {
5591 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005592 null, 0, callingUserId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005593 continue;
5594 }
5595 }
5596 } catch (RemoteException e) {
5597 // Will never happen.
5598 }
5599 }
5600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 res.add(rti);
5602 maxNum--;
5603 }
5604 }
5605 return res;
5606 }
5607 }
5608
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005609 private TaskRecord taskForIdLocked(int id) {
5610 final int N = mRecentTasks.size();
5611 for (int i=0; i<N; i++) {
5612 TaskRecord tr = mRecentTasks.get(i);
5613 if (tr.taskId == id) {
5614 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005615 }
5616 }
5617 return null;
5618 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005619
5620 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5621 synchronized (this) {
5622 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5623 "getTaskThumbnails()");
5624 TaskRecord tr = taskForIdLocked(id);
5625 if (tr != null) {
5626 return mMainStack.getTaskThumbnailsLocked(tr);
5627 }
5628 }
5629 return null;
5630 }
5631
5632 public boolean removeSubTask(int taskId, int subTaskIndex) {
5633 synchronized (this) {
5634 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5635 "removeSubTask()");
5636 long ident = Binder.clearCallingIdentity();
5637 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005638 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5639 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005640 } finally {
5641 Binder.restoreCallingIdentity(ident);
5642 }
5643 }
5644 }
5645
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005646 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5647 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005648 Intent baseIntent = new Intent(
5649 tr.intent != null ? tr.intent : tr.affinityIntent);
5650 ComponentName component = baseIntent.getComponent();
5651 if (component == null) {
5652 Slog.w(TAG, "Now component for base intent of task: " + tr);
5653 return;
5654 }
5655
5656 // Find any running services associated with this app.
5657 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005658 for (ServiceRecord sr : mServiceMap.getAllServices(tr.userId)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005659 if (sr.packageName.equals(component.getPackageName())) {
5660 services.add(sr);
5661 }
5662 }
5663
5664 // Take care of any running services associated with the app.
5665 for (int i=0; i<services.size(); i++) {
5666 ServiceRecord sr = services.get(i);
5667 if (sr.startRequested) {
5668 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005669 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005670 stopServiceLocked(sr);
5671 } else {
5672 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005673 sr.makeNextStartId(), baseIntent, null));
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005674 if (sr.app != null && sr.app.thread != null) {
5675 sendServiceArgsLocked(sr, false);
5676 }
5677 }
5678 }
5679 }
5680
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005681 if (killProcesses) {
5682 // Find any running processes associated with this app.
5683 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
5684 SparseArray<ProcessRecord> appProcs
5685 = mProcessNames.getMap().get(component.getPackageName());
5686 if (appProcs != null) {
5687 for (int i=0; i<appProcs.size(); i++) {
5688 procs.add(appProcs.valueAt(i));
5689 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005690 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005691
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005692 // Kill the running processes.
5693 for (int i=0; i<procs.size(); i++) {
5694 ProcessRecord pr = procs.get(i);
5695 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5696 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5697 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5698 pr.processName, pr.setAdj, "remove task");
5699 Process.killProcessQuiet(pr.pid);
5700 } else {
5701 pr.waitingToKill = "remove task";
5702 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005703 }
5704 }
5705 }
5706
5707 public boolean removeTask(int taskId, int flags) {
5708 synchronized (this) {
5709 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5710 "removeTask()");
5711 long ident = Binder.clearCallingIdentity();
5712 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005713 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5714 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005715 if (r != null) {
5716 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005717 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005718 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005719 } else {
5720 TaskRecord tr = null;
5721 int i=0;
5722 while (i < mRecentTasks.size()) {
5723 TaskRecord t = mRecentTasks.get(i);
5724 if (t.taskId == taskId) {
5725 tr = t;
5726 break;
5727 }
5728 i++;
5729 }
5730 if (tr != null) {
5731 if (tr.numActivities <= 0) {
5732 // Caller is just removing a recent task that is
5733 // not actively running. That is easy!
5734 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005735 cleanUpRemovedTaskLocked(tr, flags);
5736 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005737 } else {
5738 Slog.w(TAG, "removeTask: task " + taskId
5739 + " does not have activities to remove, "
5740 + " but numActivities=" + tr.numActivities
5741 + ": " + tr);
5742 }
5743 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005744 }
5745 } finally {
5746 Binder.restoreCallingIdentity(ident);
5747 }
5748 }
5749 return false;
5750 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5753 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005754 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 TaskRecord jt = startTask;
5756
5757 // First look backwards
5758 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005759 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 if (r.task != jt) {
5761 jt = r.task;
5762 if (affinity.equals(jt.affinity)) {
5763 return j;
5764 }
5765 }
5766 }
5767
5768 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005769 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770 jt = startTask;
5771 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005772 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005773 if (r.task != jt) {
5774 if (affinity.equals(jt.affinity)) {
5775 return j;
5776 }
5777 jt = r.task;
5778 }
5779 }
5780
5781 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005782 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 return N-1;
5784 }
5785
5786 return -1;
5787 }
5788
5789 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005790 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005791 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005792 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005793 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5794 "moveTaskToFront()");
5795
5796 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005797 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5798 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005799 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005800 return;
5801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802 final long origId = Binder.clearCallingIdentity();
5803 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005804 TaskRecord tr = taskForIdLocked(task);
5805 if (tr != null) {
5806 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5807 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005809 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5810 // Caller wants the home activity moved with it. To accomplish this,
5811 // we'll just move the home task to the top first.
5812 mMainStack.moveHomeToFrontLocked();
5813 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005814 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005815 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005817 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5818 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005820 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5821 mMainStack.mUserLeaving = true;
5822 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005823 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5824 // Caller wants the home activity moved with it. To accomplish this,
5825 // we'll just move the home task to the top first.
5826 mMainStack.moveHomeToFrontLocked();
5827 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005828 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 return;
5830 }
5831 }
5832 } finally {
5833 Binder.restoreCallingIdentity(origId);
5834 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005835 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 }
5837 }
5838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 public void moveTaskToBack(int task) {
5840 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5841 "moveTaskToBack()");
5842
5843 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005844 if (mMainStack.mResumedActivity != null
5845 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005846 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5847 Binder.getCallingUid(), "Task to back")) {
5848 return;
5849 }
5850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005852 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 Binder.restoreCallingIdentity(origId);
5854 }
5855 }
5856
5857 /**
5858 * Moves an activity, and all of the other activities within the same task, to the bottom
5859 * of the history stack. The activity's order within the task is unchanged.
5860 *
5861 * @param token A reference to the activity we wish to move
5862 * @param nonRoot If false then this only works if the activity is the root
5863 * of a task; if true it will work for any activity in a task.
5864 * @return Returns true if the move completed, false if not.
5865 */
5866 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005867 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 synchronized(this) {
5869 final long origId = Binder.clearCallingIdentity();
5870 int taskId = getTaskForActivityLocked(token, !nonRoot);
5871 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005872 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 }
5874 Binder.restoreCallingIdentity(origId);
5875 }
5876 return false;
5877 }
5878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005879 public void moveTaskBackwards(int task) {
5880 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5881 "moveTaskBackwards()");
5882
5883 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005884 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5885 Binder.getCallingUid(), "Task backwards")) {
5886 return;
5887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 final long origId = Binder.clearCallingIdentity();
5889 moveTaskBackwardsLocked(task);
5890 Binder.restoreCallingIdentity(origId);
5891 }
5892 }
5893
5894 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005895 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005896 }
5897
5898 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5899 synchronized(this) {
5900 return getTaskForActivityLocked(token, onlyRoot);
5901 }
5902 }
5903
5904 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005905 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005906 TaskRecord lastTask = null;
5907 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005908 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005909 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005910 if (!onlyRoot || lastTask != r.task) {
5911 return r.task.taskId;
5912 }
5913 return -1;
5914 }
5915 lastTask = r.task;
5916 }
5917
5918 return -1;
5919 }
5920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 // =========================================================
5922 // THUMBNAILS
5923 // =========================================================
5924
5925 public void reportThumbnail(IBinder token,
5926 Bitmap thumbnail, CharSequence description) {
5927 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5928 final long origId = Binder.clearCallingIdentity();
5929 sendPendingThumbnail(null, token, thumbnail, description, true);
5930 Binder.restoreCallingIdentity(origId);
5931 }
5932
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005933 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 Bitmap thumbnail, CharSequence description, boolean always) {
5935 TaskRecord task = null;
5936 ArrayList receivers = null;
5937
5938 //System.out.println("Send pending thumbnail: " + r);
5939
5940 synchronized(this) {
5941 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005942 r = mMainStack.isInStackLocked(token);
5943 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005944 return;
5945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005947 if (thumbnail == null && r.thumbHolder != null) {
5948 thumbnail = r.thumbHolder.lastThumbnail;
5949 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005950 }
5951 if (thumbnail == null && !always) {
5952 // If there is no thumbnail, and this entry is not actually
5953 // going away, then abort for now and pick up the next
5954 // thumbnail we get.
5955 return;
5956 }
5957 task = r.task;
5958
5959 int N = mPendingThumbnails.size();
5960 int i=0;
5961 while (i<N) {
5962 PendingThumbnailsRecord pr =
5963 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
5964 //System.out.println("Looking in " + pr.pendingRecords);
5965 if (pr.pendingRecords.remove(r)) {
5966 if (receivers == null) {
5967 receivers = new ArrayList();
5968 }
5969 receivers.add(pr);
5970 if (pr.pendingRecords.size() == 0) {
5971 pr.finished = true;
5972 mPendingThumbnails.remove(i);
5973 N--;
5974 continue;
5975 }
5976 }
5977 i++;
5978 }
5979 }
5980
5981 if (receivers != null) {
5982 final int N = receivers.size();
5983 for (int i=0; i<N; i++) {
5984 try {
5985 PendingThumbnailsRecord pr =
5986 (PendingThumbnailsRecord)receivers.get(i);
5987 pr.receiver.newThumbnail(
5988 task != null ? task.taskId : -1, thumbnail, description);
5989 if (pr.finished) {
5990 pr.receiver.finished();
5991 }
5992 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005993 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 }
5995 }
5996 }
5997 }
5998
5999 // =========================================================
6000 // CONTENT PROVIDERS
6001 // =========================================================
6002
Jeff Brown10e89712011-07-08 18:52:57 -07006003 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6004 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006005 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006006 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006007 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006008 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 } catch (RemoteException ex) {
6010 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006011 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006012 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6013 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006014 if (providers != null) {
6015 final int N = providers.size();
6016 for (int i=0; i<N; i++) {
6017 ProviderInfo cpi =
6018 (ProviderInfo)providers.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07006019
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006020 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006021 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 if (cpr == null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006023 cpr = new ContentProviderRecord(this, cpi, app.info, comp);
Amith Yamasani742a6712011-05-04 14:49:28 -07006024 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006026 if (DEBUG_MU)
6027 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 app.pubProviders.put(cpi.name, cpr);
6029 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006030 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 }
6032 }
6033 return providers;
6034 }
6035
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006036 /**
6037 * Check if {@link ProcessRecord} has a possible chance at accessing the
6038 * given {@link ProviderInfo}. Final permission checking is always done
6039 * in {@link ContentProvider}.
6040 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006042 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006044 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006045 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006046 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006047 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048 return null;
6049 }
6050 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006051 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006052 == PackageManager.PERMISSION_GRANTED) {
6053 return null;
6054 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006055
6056 PathPermission[] pps = cpi.pathPermissions;
6057 if (pps != null) {
6058 int i = pps.length;
6059 while (i > 0) {
6060 i--;
6061 PathPermission pp = pps[i];
6062 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006063 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006064 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006065 return null;
6066 }
6067 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006068 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006069 == PackageManager.PERMISSION_GRANTED) {
6070 return null;
6071 }
6072 }
6073 }
6074
Dianne Hackbornb424b632010-08-18 15:59:05 -07006075 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6076 if (perms != null) {
6077 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6078 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6079 return null;
6080 }
6081 }
6082 }
6083
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006084 String msg;
6085 if (!cpi.exported) {
6086 msg = "Permission Denial: opening provider " + cpi.name
6087 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6088 + ", uid=" + callingUid + ") that is not exported from uid "
6089 + cpi.applicationInfo.uid;
6090 } else {
6091 msg = "Permission Denial: opening provider " + cpi.name
6092 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6093 + ", uid=" + callingUid + ") requires "
6094 + cpi.readPermission + " or " + cpi.writePermission;
6095 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006096 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 return msg;
6098 }
6099
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006100 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6101 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006102 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006103 for (int i=0; i<r.conProviders.size(); i++) {
6104 ContentProviderConnection conn = r.conProviders.get(i);
6105 if (conn.provider == cpr) {
6106 if (DEBUG_PROVIDER) Slog.v(TAG,
6107 "Adding provider requested by "
6108 + r.processName + " from process "
6109 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6110 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6111 if (stable) {
6112 conn.stableCount++;
6113 conn.numStableIncs++;
6114 } else {
6115 conn.unstableCount++;
6116 conn.numUnstableIncs++;
6117 }
6118 return conn;
6119 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006120 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006121 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6122 if (stable) {
6123 conn.stableCount = 1;
6124 conn.numStableIncs = 1;
6125 } else {
6126 conn.unstableCount = 1;
6127 conn.numUnstableIncs = 1;
6128 }
6129 cpr.connections.add(conn);
6130 r.conProviders.add(conn);
6131 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006132 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006133 cpr.addExternalProcessHandleLocked(externalProcessToken);
6134 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006135 }
6136
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006137 boolean decProviderCountLocked(ContentProviderConnection conn,
6138 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6139 if (conn != null) {
6140 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006141 if (DEBUG_PROVIDER) Slog.v(TAG,
6142 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006143 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006144 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006145 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6146 if (stable) {
6147 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006148 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006149 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006150 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006151 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6152 cpr.connections.remove(conn);
6153 conn.client.conProviders.remove(conn);
6154 return true;
6155 }
6156 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006157 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006158 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006159 return false;
6160 }
6161
Amith Yamasani742a6712011-05-04 14:49:28 -07006162 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006163 String name, IBinder token, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006165 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 ProviderInfo cpi = null;
6167
6168 synchronized(this) {
6169 ProcessRecord r = null;
6170 if (caller != null) {
6171 r = getRecordForAppLocked(caller);
6172 if (r == null) {
6173 throw new SecurityException(
6174 "Unable to find app for caller " + caller
6175 + " (pid=" + Binder.getCallingPid()
6176 + ") when getting content provider " + name);
6177 }
6178 }
6179
6180 // First check if this content provider has been published...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006181 int userId = UserId.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006182 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006183 boolean providerRunning = cpr != null;
6184 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006186 String msg;
6187 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6188 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 }
6190
6191 if (r != null && cpr.canRunHere(r)) {
6192 // This provider has been published or is in the process
6193 // of being published... but it is also allowed to run
6194 // in the caller's process, so don't make a connection
6195 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006196 ContentProviderHolder holder = cpr.newHolder(null);
6197 // don't give caller the provider object, it needs
6198 // to make its own.
6199 holder.provider = null;
6200 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 }
6202
6203 final long origId = Binder.clearCallingIdentity();
6204
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006205 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006207 conn = incProviderCountLocked(r, cpr, token, stable);
6208 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006209 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006210 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006211 // make sure to count it as being accessed and thus
6212 // back up on the LRU list. This is good because
6213 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006214 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006215 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006216 }
6217
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006218 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006219 if (false) {
6220 if (cpr.name.flattenToShortString().equals(
6221 "com.android.providers.calendar/.CalendarProvider2")) {
6222 Slog.v(TAG, "****************** KILLING "
6223 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006224 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006225 }
6226 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006227 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006228 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6229 // NOTE: there is still a race here where a signal could be
6230 // pending on the process even though we managed to update its
6231 // adj level. Not sure what to do about this, but at least
6232 // the race is now smaller.
6233 if (!success) {
6234 // Uh oh... it looks like the provider's process
6235 // has been killed on us. We need to wait for a new
6236 // process to be started, and make sure its death
6237 // doesn't kill our process.
6238 Slog.i(TAG,
6239 "Existing provider " + cpr.name.flattenToShortString()
6240 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006241 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006242 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006243 if (!lastRef) {
6244 // This wasn't the last ref our process had on
6245 // the provider... we have now been killed, bail.
6246 return null;
6247 }
6248 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006249 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 }
6252
6253 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006256 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006258 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006259 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006260 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261 } catch (RemoteException ex) {
6262 }
6263 if (cpi == null) {
6264 return null;
6265 }
Amith Yamasania4a54e22012-04-16 15:44:19 -07006266 if (isSingleton(cpi.processName, cpi.applicationInfo)) {
6267 userId = 0;
6268 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006269 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006270
Dianne Hackbornb424b632010-08-18 15:59:05 -07006271 String msg;
6272 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6273 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 }
6275
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006276 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006277 && !cpi.processName.equals("system")) {
6278 // If this content provider does not run in the system
6279 // process, and the system is not yet ready to run other
6280 // processes, then fail fast instead of hanging.
6281 throw new IllegalArgumentException(
6282 "Attempt to launch content provider before system ready");
6283 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006284
6285 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006286 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006287 final boolean firstClass = cpr == null;
6288 if (firstClass) {
6289 try {
6290 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006291 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 getApplicationInfo(
6293 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006294 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006296 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 + cpi.name);
6298 return null;
6299 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006300 ai = getAppInfoForUser(ai, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006301 cpr = new ContentProviderRecord(this, cpi, ai, comp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 } catch (RemoteException ex) {
6303 // pm is in same process, this will never happen.
6304 }
6305 }
6306
6307 if (r != null && cpr.canRunHere(r)) {
6308 // If this is a multiprocess provider, then just return its
6309 // info and allow the caller to instantiate it. Only do
6310 // this if the provider is the same user as the caller's
6311 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006312 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 }
6314
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006315 if (DEBUG_PROVIDER) {
6316 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006317 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006318 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 }
6320
6321 // This is single process, and our app is now connecting to it.
6322 // See if we are already in the process of launching this
6323 // provider.
6324 final int N = mLaunchingProviders.size();
6325 int i;
6326 for (i=0; i<N; i++) {
6327 if (mLaunchingProviders.get(i) == cpr) {
6328 break;
6329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330 }
6331
6332 // If the provider is not already being launched, then get it
6333 // started.
6334 if (i >= N) {
6335 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006336
6337 try {
6338 // Content provider is now in use, its package can't be stopped.
6339 try {
6340 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006341 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006342 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006343 } catch (IllegalArgumentException e) {
6344 Slog.w(TAG, "Failed trying to unstop package "
6345 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006346 }
6347
6348 ProcessRecord proc = startProcessLocked(cpi.processName,
6349 cpr.appInfo, false, 0, "content provider",
6350 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006351 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006352 if (proc == null) {
6353 Slog.w(TAG, "Unable to launch app "
6354 + cpi.applicationInfo.packageName + "/"
6355 + cpi.applicationInfo.uid + " for provider "
6356 + name + ": process is bad");
6357 return null;
6358 }
6359 cpr.launchingApp = proc;
6360 mLaunchingProviders.add(cpr);
6361 } finally {
6362 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006364 }
6365
6366 // Make sure the provider is published (the same provider class
6367 // may be published under multiple names).
6368 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006369 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006371
Amith Yamasani742a6712011-05-04 14:49:28 -07006372 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006373 conn = incProviderCountLocked(r, cpr, token, stable);
6374 if (conn != null) {
6375 conn.waiting = true;
6376 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006377 }
6378 }
6379
6380 // Wait for the provider to be published...
6381 synchronized (cpr) {
6382 while (cpr.provider == null) {
6383 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006384 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 + cpi.applicationInfo.packageName + "/"
6386 + cpi.applicationInfo.uid + " for provider "
6387 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006388 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 cpi.applicationInfo.packageName,
6390 cpi.applicationInfo.uid, name);
6391 return null;
6392 }
6393 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006394 if (DEBUG_MU) {
6395 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6396 + cpr.launchingApp);
6397 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006398 if (conn != null) {
6399 conn.waiting = true;
6400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 cpr.wait();
6402 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006403 } finally {
6404 if (conn != null) {
6405 conn.waiting = false;
6406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 }
6408 }
6409 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006410 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 }
6412
6413 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006414 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006415 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 if (caller == null) {
6417 String msg = "null IApplicationThread when getting content provider "
6418 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006419 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 throw new SecurityException(msg);
6421 }
6422
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006423 return getContentProviderImpl(caller, name, null, stable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006424 }
6425
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006426 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6427 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6428 "Do not have permission in call getContentProviderExternal()");
6429 return getContentProviderExternalUnchecked(name, token);
6430 }
6431
6432 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006433 return getContentProviderImpl(null, name, token, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 }
6435
6436 /**
6437 * Drop a content provider from a ProcessRecord's bookkeeping
6438 * @param cpr
6439 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006440 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006441 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006443 ContentProviderConnection conn;
6444 try {
6445 conn = (ContentProviderConnection)connection;
6446 } catch (ClassCastException e) {
6447 String msg ="removeContentProvider: " + connection
6448 + " not a ContentProviderConnection";
6449 Slog.w(TAG, msg);
6450 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006452 if (conn == null) {
6453 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006455 if (decProviderCountLocked(conn, null, null, stable)) {
6456 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 }
6459 }
6460
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006461 public void removeContentProviderExternal(String name, IBinder token) {
6462 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6463 "Do not have permission in call removeContentProviderExternal()");
6464 removeContentProviderExternalUnchecked(name, token);
6465 }
6466
6467 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006468 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006469 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6470 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 if(cpr == null) {
6472 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006473 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 return;
6475 }
6476
6477 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006478 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006479 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6480 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006481 if (localCpr.hasExternalProcessHandles()) {
6482 if (localCpr.removeExternalProcessHandleLocked(token)) {
6483 updateOomAdjLocked();
6484 } else {
6485 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6486 + " with no external reference for token: "
6487 + token + ".");
6488 }
6489 } else {
6490 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6491 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 }
6494 }
6495
6496 public final void publishContentProviders(IApplicationThread caller,
6497 List<ContentProviderHolder> providers) {
6498 if (providers == null) {
6499 return;
6500 }
6501
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006502 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006503 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006504 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006505 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006506 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006507 if (r == null) {
6508 throw new SecurityException(
6509 "Unable to find app for caller " + caller
6510 + " (pid=" + Binder.getCallingPid()
6511 + ") when publishing content providers");
6512 }
6513
6514 final long origId = Binder.clearCallingIdentity();
6515
6516 final int N = providers.size();
6517 for (int i=0; i<N; i++) {
6518 ContentProviderHolder src = providers.get(i);
6519 if (src == null || src.info == null || src.provider == null) {
6520 continue;
6521 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006522 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006523 if (DEBUG_MU)
6524 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006526 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006527 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 String names[] = dst.info.authority.split(";");
6529 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006530 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 }
6532
6533 int NL = mLaunchingProviders.size();
6534 int j;
6535 for (j=0; j<NL; j++) {
6536 if (mLaunchingProviders.get(j) == dst) {
6537 mLaunchingProviders.remove(j);
6538 j--;
6539 NL--;
6540 }
6541 }
6542 synchronized (dst) {
6543 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006544 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006545 dst.notifyAll();
6546 }
6547 updateOomAdjLocked(r);
6548 }
6549 }
6550
6551 Binder.restoreCallingIdentity(origId);
6552 }
6553 }
6554
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006555 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6556 ContentProviderConnection conn;
6557 try {
6558 conn = (ContentProviderConnection)connection;
6559 } catch (ClassCastException e) {
6560 String msg ="refContentProvider: " + connection
6561 + " not a ContentProviderConnection";
6562 Slog.w(TAG, msg);
6563 throw new IllegalArgumentException(msg);
6564 }
6565 if (conn == null) {
6566 throw new NullPointerException("connection is null");
6567 }
6568
6569 synchronized (this) {
6570 if (stable > 0) {
6571 conn.numStableIncs += stable;
6572 }
6573 stable = conn.stableCount + stable;
6574 if (stable < 0) {
6575 throw new IllegalStateException("stableCount < 0: " + stable);
6576 }
6577
6578 if (unstable > 0) {
6579 conn.numUnstableIncs += unstable;
6580 }
6581 unstable = conn.unstableCount + unstable;
6582 if (unstable < 0) {
6583 throw new IllegalStateException("unstableCount < 0: " + unstable);
6584 }
6585
6586 if ((stable+unstable) <= 0) {
6587 throw new IllegalStateException("ref counts can't go to zero here: stable="
6588 + stable + " unstable=" + unstable);
6589 }
6590 conn.stableCount = stable;
6591 conn.unstableCount = unstable;
6592 return !conn.dead;
6593 }
6594 }
6595
6596 public void unstableProviderDied(IBinder connection) {
6597 ContentProviderConnection conn;
6598 try {
6599 conn = (ContentProviderConnection)connection;
6600 } catch (ClassCastException e) {
6601 String msg ="refContentProvider: " + connection
6602 + " not a ContentProviderConnection";
6603 Slog.w(TAG, msg);
6604 throw new IllegalArgumentException(msg);
6605 }
6606 if (conn == null) {
6607 throw new NullPointerException("connection is null");
6608 }
6609
6610 // Safely retrieve the content provider associated with the connection.
6611 IContentProvider provider;
6612 synchronized (this) {
6613 provider = conn.provider.provider;
6614 }
6615
6616 if (provider == null) {
6617 // Um, yeah, we're way ahead of you.
6618 return;
6619 }
6620
6621 // Make sure the caller is being honest with us.
6622 if (provider.asBinder().pingBinder()) {
6623 // Er, no, still looks good to us.
6624 synchronized (this) {
6625 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6626 + " says " + conn + " died, but we don't agree");
6627 return;
6628 }
6629 }
6630
6631 // Well look at that! It's dead!
6632 synchronized (this) {
6633 if (conn.provider.provider != provider) {
6634 // But something changed... good enough.
6635 return;
6636 }
6637
6638 ProcessRecord proc = conn.provider.proc;
6639 if (proc == null || proc.thread == null) {
6640 // Seems like the process is already cleaned up.
6641 return;
6642 }
6643
6644 // As far as we're concerned, this is just like receiving a
6645 // death notification... just a bit prematurely.
6646 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6647 + ") early provider death");
6648 appDiedLocked(proc, proc.pid, proc.thread);
6649 }
6650 }
6651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006652 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006653 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006654 synchronized (mSelf) {
6655 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6656 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006657 if (providers != null) {
6658 for (int i=providers.size()-1; i>=0; i--) {
6659 ProviderInfo pi = (ProviderInfo)providers.get(i);
6660 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6661 Slog.w(TAG, "Not installing system proc provider " + pi.name
6662 + ": not system .apk");
6663 providers.remove(i);
6664 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006665 }
6666 }
6667 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006668 if (providers != null) {
6669 mSystemThread.installSystemProviders(providers);
6670 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006671
6672 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006673
6674 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 }
6676
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006677 /**
6678 * Allows app to retrieve the MIME type of a URI without having permission
6679 * to access its content provider.
6680 *
6681 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6682 *
6683 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6684 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6685 */
6686 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006687 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006688 final String name = uri.getAuthority();
6689 final long ident = Binder.clearCallingIdentity();
6690 ContentProviderHolder holder = null;
6691
6692 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006693 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006694 if (holder != null) {
6695 return holder.provider.getType(uri);
6696 }
6697 } catch (RemoteException e) {
6698 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6699 return null;
6700 } finally {
6701 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006702 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006703 }
6704 Binder.restoreCallingIdentity(ident);
6705 }
6706
6707 return null;
6708 }
6709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 // =========================================================
6711 // GLOBAL MANAGEMENT
6712 // =========================================================
6713
6714 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006715 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006716 String proc = customProcess != null ? customProcess : info.processName;
6717 BatteryStatsImpl.Uid.Proc ps = null;
6718 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006719 int uid = info.uid;
6720 if (isolated) {
6721 int userId = UserId.getUserId(uid);
6722 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6723 uid = 0;
6724 while (true) {
6725 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6726 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6727 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6728 }
6729 uid = UserId.getUid(userId, mNextIsolatedProcessUid);
6730 mNextIsolatedProcessUid++;
6731 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6732 // No process for this uid, use it.
6733 break;
6734 }
6735 stepsLeft--;
6736 if (stepsLeft <= 0) {
6737 return null;
6738 }
6739 }
6740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741 synchronized (stats) {
6742 ps = stats.getProcessStatsLocked(info.uid, proc);
6743 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006744 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 }
6746
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006747 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6748 ProcessRecord app;
6749 if (!isolated) {
6750 app = getProcessRecordLocked(info.processName, info.uid);
6751 } else {
6752 app = null;
6753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754
6755 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006756 app = newProcessRecordLocked(null, info, null, isolated);
6757 mProcessNames.put(info.processName, app.uid, app);
6758 if (isolated) {
6759 mIsolatedProcesses.put(app.uid, app);
6760 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006761 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006762 }
6763
Dianne Hackborne7f97212011-02-24 14:40:20 -08006764 // This package really, really can not be stopped.
6765 try {
6766 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006767 info.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006768 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006769 } catch (IllegalArgumentException e) {
6770 Slog.w(TAG, "Failed trying to unstop package "
6771 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006772 }
6773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6775 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6776 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006777 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778 }
6779 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6780 mPersistentStartingProcesses.add(app);
6781 startProcessLocked(app, "added application", app.processName);
6782 }
6783
6784 return app;
6785 }
6786
6787 public void unhandledBack() {
6788 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6789 "unhandledBack()");
6790
6791 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006792 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006793 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006794 TAG, "Performing unhandledBack(): stack size = " + count);
6795 if (count > 1) {
6796 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006797 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006798 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6799 Binder.restoreCallingIdentity(origId);
6800 }
6801 }
6802 }
6803
6804 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006805 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006806 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006807 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006808 ParcelFileDescriptor pfd = null;
6809 if (cph != null) {
6810 // We record the binder invoker's uid in thread-local storage before
6811 // going to the content provider to open the file. Later, in the code
6812 // that handles all permissions checks, we look for this uid and use
6813 // that rather than the Activity Manager's own uid. The effect is that
6814 // we do the check against the caller's permissions even though it looks
6815 // to the content provider like the Activity Manager itself is making
6816 // the request.
6817 sCallerIdentity.set(new Identity(
6818 Binder.getCallingPid(), Binder.getCallingUid()));
6819 try {
6820 pfd = cph.provider.openFile(uri, "r");
6821 } catch (FileNotFoundException e) {
6822 // do nothing; pfd will be returned null
6823 } finally {
6824 // Ensure that whatever happens, we clean up the identity state
6825 sCallerIdentity.remove();
6826 }
6827
6828 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006829 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006830 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006831 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006832 }
6833 return pfd;
6834 }
6835
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006836 // Actually is sleeping or shutting down or whatever else in the future
6837 // is an inactive state.
6838 public boolean isSleeping() {
6839 return mSleeping || mShuttingDown;
6840 }
6841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006842 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006843 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6844 != PackageManager.PERMISSION_GRANTED) {
6845 throw new SecurityException("Requires permission "
6846 + android.Manifest.permission.DEVICE_POWER);
6847 }
6848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006849 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006850 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006851 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006852
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006853 if (!mSleeping) {
6854 mSleeping = true;
6855 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006856
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006857 // Initialize the wake times of all processes.
6858 checkExcessivePowerUsageLocked(false);
6859 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6860 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6861 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 }
6864 }
6865
Dianne Hackborn55280a92009-05-07 15:53:46 -07006866 public boolean shutdown(int timeout) {
6867 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6868 != PackageManager.PERMISSION_GRANTED) {
6869 throw new SecurityException("Requires permission "
6870 + android.Manifest.permission.SHUTDOWN);
6871 }
6872
6873 boolean timedout = false;
6874
6875 synchronized(this) {
6876 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006877 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006878
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006879 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006880 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006881 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006882 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006883 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006884 long delay = endTime - System.currentTimeMillis();
6885 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006886 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006887 timedout = true;
6888 break;
6889 }
6890 try {
6891 this.wait();
6892 } catch (InterruptedException e) {
6893 }
6894 }
6895 }
6896 }
6897
6898 mUsageStatsService.shutdown();
6899 mBatteryStatsService.shutdown();
6900
6901 return timedout;
6902 }
6903
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006904 public final void activitySlept(IBinder token) {
6905 if (localLOGV) Slog.v(
6906 TAG, "Activity slept: token=" + token);
6907
6908 ActivityRecord r = null;
6909
6910 final long origId = Binder.clearCallingIdentity();
6911
6912 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006913 r = mMainStack.isInStackLocked(token);
6914 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006915 mMainStack.activitySleptLocked(r);
6916 }
6917 }
6918
6919 Binder.restoreCallingIdentity(origId);
6920 }
6921
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006922 private void comeOutOfSleepIfNeededLocked() {
6923 if (!mWentToSleep && !mLockScreenShown) {
6924 if (mSleeping) {
6925 mSleeping = false;
6926 mMainStack.awakeFromSleepingLocked();
6927 mMainStack.resumeTopActivityLocked(null);
6928 }
6929 }
6930 }
6931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006932 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006933 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6934 != PackageManager.PERMISSION_GRANTED) {
6935 throw new SecurityException("Requires permission "
6936 + android.Manifest.permission.DEVICE_POWER);
6937 }
6938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006939 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006940 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07006941 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006942 comeOutOfSleepIfNeededLocked();
6943 }
6944 }
6945
Jeff Brownc042ee22012-05-08 13:03:42 -07006946 private void updateEventDispatchingLocked() {
6947 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
6948 }
6949
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006950 public void setLockScreenShown(boolean shown) {
6951 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6952 != PackageManager.PERMISSION_GRANTED) {
6953 throw new SecurityException("Requires permission "
6954 + android.Manifest.permission.DEVICE_POWER);
6955 }
6956
6957 synchronized(this) {
6958 mLockScreenShown = shown;
6959 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006960 }
6961 }
6962
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006963 public void stopAppSwitches() {
6964 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6965 != PackageManager.PERMISSION_GRANTED) {
6966 throw new SecurityException("Requires permission "
6967 + android.Manifest.permission.STOP_APP_SWITCHES);
6968 }
6969
6970 synchronized(this) {
6971 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
6972 + APP_SWITCH_DELAY_TIME;
6973 mDidAppSwitch = false;
6974 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6975 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
6976 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
6977 }
6978 }
6979
6980 public void resumeAppSwitches() {
6981 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
6982 != PackageManager.PERMISSION_GRANTED) {
6983 throw new SecurityException("Requires permission "
6984 + android.Manifest.permission.STOP_APP_SWITCHES);
6985 }
6986
6987 synchronized(this) {
6988 // Note that we don't execute any pending app switches... we will
6989 // let those wait until either the timeout, or the next start
6990 // activity request.
6991 mAppSwitchesAllowedTime = 0;
6992 }
6993 }
6994
6995 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
6996 String name) {
6997 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
6998 return true;
6999 }
7000
7001 final int perm = checkComponentPermission(
7002 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007003 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007004 if (perm == PackageManager.PERMISSION_GRANTED) {
7005 return true;
7006 }
7007
Joe Onorato8a9b2202010-02-26 18:56:32 -08007008 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007009 return false;
7010 }
7011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007012 public void setDebugApp(String packageName, boolean waitForDebugger,
7013 boolean persistent) {
7014 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7015 "setDebugApp()");
7016
7017 // Note that this is not really thread safe if there are multiple
7018 // callers into it at the same time, but that's not a situation we
7019 // care about.
7020 if (persistent) {
7021 final ContentResolver resolver = mContext.getContentResolver();
7022 Settings.System.putString(
7023 resolver, Settings.System.DEBUG_APP,
7024 packageName);
7025 Settings.System.putInt(
7026 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7027 waitForDebugger ? 1 : 0);
7028 }
7029
7030 synchronized (this) {
7031 if (!persistent) {
7032 mOrigDebugApp = mDebugApp;
7033 mOrigWaitForDebugger = mWaitForDebugger;
7034 }
7035 mDebugApp = packageName;
7036 mWaitForDebugger = waitForDebugger;
7037 mDebugTransient = !persistent;
7038 if (packageName != null) {
7039 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07007040 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 Binder.restoreCallingIdentity(origId);
7042 }
7043 }
7044 }
7045
Siva Velusamy92a8b222012-03-09 16:24:04 -08007046 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7047 synchronized (this) {
7048 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7049 if (!isDebuggable) {
7050 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7051 throw new SecurityException("Process not debuggable: " + app.packageName);
7052 }
7053 }
7054
7055 mOpenGlTraceApp = processName;
7056 }
7057 }
7058
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007059 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7060 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7061 synchronized (this) {
7062 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7063 if (!isDebuggable) {
7064 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7065 throw new SecurityException("Process not debuggable: " + app.packageName);
7066 }
7067 }
7068 mProfileApp = processName;
7069 mProfileFile = profileFile;
7070 if (mProfileFd != null) {
7071 try {
7072 mProfileFd.close();
7073 } catch (IOException e) {
7074 }
7075 mProfileFd = null;
7076 }
7077 mProfileFd = profileFd;
7078 mProfileType = 0;
7079 mAutoStopProfiler = autoStopProfiler;
7080 }
7081 }
7082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 public void setAlwaysFinish(boolean enabled) {
7084 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7085 "setAlwaysFinish()");
7086
7087 Settings.System.putInt(
7088 mContext.getContentResolver(),
7089 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7090
7091 synchronized (this) {
7092 mAlwaysFinishActivities = enabled;
7093 }
7094 }
7095
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007096 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007097 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007098 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007099 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007100 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007101 }
7102 }
7103
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007104 public boolean isUserAMonkey() {
7105 // For now the fact that there is a controller implies
7106 // we have a monkey.
7107 synchronized (this) {
7108 return mController != null;
7109 }
7110 }
7111
Jeff Sharkeya4620792011-05-20 15:29:23 -07007112 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007113 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7114 "registerProcessObserver()");
7115 synchronized (this) {
7116 mProcessObservers.register(observer);
7117 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007118 }
7119
7120 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007121 synchronized (this) {
7122 mProcessObservers.unregister(observer);
7123 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007124 }
7125
Daniel Sandler69a48172010-06-23 16:29:36 -04007126 public void setImmersive(IBinder token, boolean immersive) {
7127 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007128 ActivityRecord r = mMainStack.isInStackLocked(token);
7129 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007130 throw new IllegalArgumentException();
7131 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007132 r.immersive = immersive;
7133 }
7134 }
7135
7136 public boolean isImmersive(IBinder token) {
7137 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007138 ActivityRecord r = mMainStack.isInStackLocked(token);
7139 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007140 throw new IllegalArgumentException();
7141 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007142 return r.immersive;
7143 }
7144 }
7145
7146 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007147 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007148 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007149 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007150 return (r != null) ? r.immersive : false;
7151 }
7152 }
7153
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007154 public final void enterSafeMode() {
7155 synchronized(this) {
7156 // It only makes sense to do this before the system is ready
7157 // and started launching other packages.
7158 if (!mSystemReady) {
7159 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007160 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007161 } catch (RemoteException e) {
7162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007163 }
7164 }
7165 }
7166
Jeff Brownb09abc12011-01-13 21:08:27 -08007167 public final void showSafeModeOverlay() {
7168 View v = LayoutInflater.from(mContext).inflate(
7169 com.android.internal.R.layout.safe_mode, null);
7170 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7171 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7172 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7173 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
7174 lp.gravity = Gravity.BOTTOM | Gravity.LEFT;
7175 lp.format = v.getBackground().getOpacity();
7176 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7177 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7178 ((WindowManager)mContext.getSystemService(
7179 Context.WINDOW_SERVICE)).addView(v, lp);
7180 }
7181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007182 public void noteWakeupAlarm(IIntentSender sender) {
7183 if (!(sender instanceof PendingIntentRecord)) {
7184 return;
7185 }
7186 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7187 synchronized (stats) {
7188 if (mBatteryStatsService.isOnBattery()) {
7189 mBatteryStatsService.enforceCallingPermission();
7190 PendingIntentRecord rec = (PendingIntentRecord)sender;
7191 int MY_UID = Binder.getCallingUid();
7192 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7193 BatteryStatsImpl.Uid.Pkg pkg =
7194 stats.getPackageStatsLocked(uid, rec.key.packageName);
7195 pkg.incWakeupsLocked();
7196 }
7197 }
7198 }
7199
Dianne Hackborn64825172011-03-02 21:32:58 -08007200 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007201 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007202 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007203 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007204 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 // XXX Note: don't acquire main activity lock here, because the window
7206 // manager calls in with its locks held.
7207
7208 boolean killed = false;
7209 synchronized (mPidsSelfLocked) {
7210 int[] types = new int[pids.length];
7211 int worstType = 0;
7212 for (int i=0; i<pids.length; i++) {
7213 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7214 if (proc != null) {
7215 int type = proc.setAdj;
7216 types[i] = type;
7217 if (type > worstType) {
7218 worstType = type;
7219 }
7220 }
7221 }
7222
Dianne Hackborn64825172011-03-02 21:32:58 -08007223 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007224 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007225 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7226 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007227 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007228 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007229
7230 // If this is not a secure call, don't let it kill processes that
7231 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007232 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7233 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007234 }
7235
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007236 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007237 for (int i=0; i<pids.length; i++) {
7238 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7239 if (proc == null) {
7240 continue;
7241 }
7242 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007243 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007244 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007245 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7246 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007247 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007248 proc.killedBackground = true;
7249 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007250 }
7251 }
7252 }
7253 return killed;
7254 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007255
7256 @Override
7257 public boolean killProcessesBelowForeground(String reason) {
7258 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7259 throw new SecurityException("killProcessesBelowForeground() only available to system");
7260 }
7261
7262 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7263 }
7264
7265 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7266 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7267 throw new SecurityException("killProcessesBelowAdj() only available to system");
7268 }
7269
7270 boolean killed = false;
7271 synchronized (mPidsSelfLocked) {
7272 final int size = mPidsSelfLocked.size();
7273 for (int i = 0; i < size; i++) {
7274 final int pid = mPidsSelfLocked.keyAt(i);
7275 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7276 if (proc == null) continue;
7277
7278 final int adj = proc.setAdj;
7279 if (adj > belowAdj && !proc.killedBackground) {
7280 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7281 EventLog.writeEvent(
7282 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7283 killed = true;
7284 proc.killedBackground = true;
7285 Process.killProcessQuiet(pid);
7286 }
7287 }
7288 }
7289 return killed;
7290 }
7291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007292 public final void startRunning(String pkg, String cls, String action,
7293 String data) {
7294 synchronized(this) {
7295 if (mStartRunning) {
7296 return;
7297 }
7298 mStartRunning = true;
7299 mTopComponent = pkg != null && cls != null
7300 ? new ComponentName(pkg, cls) : null;
7301 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7302 mTopData = data;
7303 if (!mSystemReady) {
7304 return;
7305 }
7306 }
7307
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007308 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007309 }
7310
7311 private void retrieveSettings() {
7312 final ContentResolver resolver = mContext.getContentResolver();
7313 String debugApp = Settings.System.getString(
7314 resolver, Settings.System.DEBUG_APP);
7315 boolean waitForDebugger = Settings.System.getInt(
7316 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7317 boolean alwaysFinishActivities = Settings.System.getInt(
7318 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7319
7320 Configuration configuration = new Configuration();
7321 Settings.System.getConfiguration(resolver, configuration);
7322
7323 synchronized (this) {
7324 mDebugApp = mOrigDebugApp = debugApp;
7325 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7326 mAlwaysFinishActivities = alwaysFinishActivities;
7327 // This happens before any activities are started, so we can
7328 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007329 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007330 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007331 }
7332 }
7333
7334 public boolean testIsSystemReady() {
7335 // no need to synchronize(this) just to read & return the value
7336 return mSystemReady;
7337 }
7338
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007339 private static File getCalledPreBootReceiversFile() {
7340 File dataDir = Environment.getDataDirectory();
7341 File systemDir = new File(dataDir, "system");
7342 File fname = new File(systemDir, "called_pre_boots.dat");
7343 return fname;
7344 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007345
7346 static final int LAST_DONE_VERSION = 10000;
7347
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007348 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7349 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7350 File file = getCalledPreBootReceiversFile();
7351 FileInputStream fis = null;
7352 try {
7353 fis = new FileInputStream(file);
7354 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007355 int fvers = dis.readInt();
7356 if (fvers == LAST_DONE_VERSION) {
7357 String vers = dis.readUTF();
7358 String codename = dis.readUTF();
7359 String build = dis.readUTF();
7360 if (android.os.Build.VERSION.RELEASE.equals(vers)
7361 && android.os.Build.VERSION.CODENAME.equals(codename)
7362 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7363 int num = dis.readInt();
7364 while (num > 0) {
7365 num--;
7366 String pkg = dis.readUTF();
7367 String cls = dis.readUTF();
7368 lastDoneReceivers.add(new ComponentName(pkg, cls));
7369 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007370 }
7371 }
7372 } catch (FileNotFoundException e) {
7373 } catch (IOException e) {
7374 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7375 } finally {
7376 if (fis != null) {
7377 try {
7378 fis.close();
7379 } catch (IOException e) {
7380 }
7381 }
7382 }
7383 return lastDoneReceivers;
7384 }
7385
7386 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7387 File file = getCalledPreBootReceiversFile();
7388 FileOutputStream fos = null;
7389 DataOutputStream dos = null;
7390 try {
7391 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7392 fos = new FileOutputStream(file);
7393 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007394 dos.writeInt(LAST_DONE_VERSION);
7395 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007396 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007397 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007398 dos.writeInt(list.size());
7399 for (int i=0; i<list.size(); i++) {
7400 dos.writeUTF(list.get(i).getPackageName());
7401 dos.writeUTF(list.get(i).getClassName());
7402 }
7403 } catch (IOException e) {
7404 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7405 file.delete();
7406 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007407 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007408 if (dos != null) {
7409 try {
7410 dos.close();
7411 } catch (IOException e) {
7412 // TODO Auto-generated catch block
7413 e.printStackTrace();
7414 }
7415 }
7416 }
7417 }
7418
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007419 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007420 synchronized(this) {
7421 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007422 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007423 return;
7424 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007425
7426 // Check to see if there are any update receivers to run.
7427 if (!mDidUpdate) {
7428 if (mWaitingUpdate) {
7429 return;
7430 }
7431 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7432 List<ResolveInfo> ris = null;
7433 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007434 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007435 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007436 } catch (RemoteException e) {
7437 }
7438 if (ris != null) {
7439 for (int i=ris.size()-1; i>=0; i--) {
7440 if ((ris.get(i).activityInfo.applicationInfo.flags
7441 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7442 ris.remove(i);
7443 }
7444 }
7445 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007446
7447 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7448
7449 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007450 for (int i=0; i<ris.size(); i++) {
7451 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007452 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7453 if (lastDoneReceivers.contains(comp)) {
7454 ris.remove(i);
7455 i--;
7456 }
7457 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007458
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007459 for (int i=0; i<ris.size(); i++) {
7460 ActivityInfo ai = ris.get(i).activityInfo;
7461 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7462 doneReceivers.add(comp);
7463 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007464 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007465 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007466 finisher = new IIntentReceiver.Stub() {
7467 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007468 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007469 boolean sticky) {
7470 // The raw IIntentReceiver interface is called
7471 // with the AM lock held, so redispatch to
7472 // execute our code without the lock.
7473 mHandler.post(new Runnable() {
7474 public void run() {
7475 synchronized (ActivityManagerService.this) {
7476 mDidUpdate = true;
7477 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007478 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007479 showBootMessage(mContext.getText(
7480 R.string.android_upgrading_complete),
7481 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007482 systemReady(goingCallback);
7483 }
7484 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007485 }
7486 };
7487 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007488 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Amith Yamasani742a6712011-05-04 14:49:28 -07007489 /* TODO: Send this to all users */
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007490 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007491 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Amith Yamasanic600e21f2012-02-14 16:08:07 -08007492 0 /* UserId zero */);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007493 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007494 mWaitingUpdate = true;
7495 }
7496 }
7497 }
7498 if (mWaitingUpdate) {
7499 return;
7500 }
7501 mDidUpdate = true;
7502 }
7503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007504 mSystemReady = true;
7505 if (!mStartRunning) {
7506 return;
7507 }
7508 }
7509
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007510 ArrayList<ProcessRecord> procsToKill = null;
7511 synchronized(mPidsSelfLocked) {
7512 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7513 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7514 if (!isAllowedWhileBooting(proc.info)){
7515 if (procsToKill == null) {
7516 procsToKill = new ArrayList<ProcessRecord>();
7517 }
7518 procsToKill.add(proc);
7519 }
7520 }
7521 }
7522
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007523 synchronized(this) {
7524 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007525 for (int i=procsToKill.size()-1; i>=0; i--) {
7526 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007527 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007528 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007529 }
7530 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007531
7532 // Now that we have cleaned up any update processes, we
7533 // are ready to start launching real processes and know that
7534 // we won't trample on them any more.
7535 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007536 }
7537
Joe Onorato8a9b2202010-02-26 18:56:32 -08007538 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007539 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007540 SystemClock.uptimeMillis());
7541
7542 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007543 // Make sure we have no pre-ready processes sitting around.
7544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007545 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7546 ResolveInfo ri = mContext.getPackageManager()
7547 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007548 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007549 CharSequence errorMsg = null;
7550 if (ri != null) {
7551 ActivityInfo ai = ri.activityInfo;
7552 ApplicationInfo app = ai.applicationInfo;
7553 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7554 mTopAction = Intent.ACTION_FACTORY_TEST;
7555 mTopData = null;
7556 mTopComponent = new ComponentName(app.packageName,
7557 ai.name);
7558 } else {
7559 errorMsg = mContext.getResources().getText(
7560 com.android.internal.R.string.factorytest_not_system);
7561 }
7562 } else {
7563 errorMsg = mContext.getResources().getText(
7564 com.android.internal.R.string.factorytest_no_action);
7565 }
7566 if (errorMsg != null) {
7567 mTopAction = null;
7568 mTopData = null;
7569 mTopComponent = null;
7570 Message msg = Message.obtain();
7571 msg.what = SHOW_FACTORY_ERROR_MSG;
7572 msg.getData().putCharSequence("msg", errorMsg);
7573 mHandler.sendMessage(msg);
7574 }
7575 }
7576 }
7577
7578 retrieveSettings();
7579
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007580 if (goingCallback != null) goingCallback.run();
7581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007582 synchronized (this) {
7583 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7584 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007585 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007586 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 if (apps != null) {
7588 int N = apps.size();
7589 int i;
7590 for (i=0; i<N; i++) {
7591 ApplicationInfo info
7592 = (ApplicationInfo)apps.get(i);
7593 if (info != null &&
7594 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007595 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007596 }
7597 }
7598 }
7599 } catch (RemoteException ex) {
7600 // pm is in same process, this will never happen.
7601 }
7602 }
7603
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007604 // Start up initial activity.
7605 mBooting = true;
7606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007607 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007608 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007609 Message msg = Message.obtain();
7610 msg.what = SHOW_UID_ERROR_MSG;
7611 mHandler.sendMessage(msg);
7612 }
7613 } catch (RemoteException e) {
7614 }
7615
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007616 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007617 }
7618 }
7619
Dan Egnorb7f03672009-12-09 16:22:32 -08007620 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007621 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007622 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007623 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007624 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007625 startAppProblemLocked(app);
7626 app.stopFreezingAllLocked();
7627 return handleAppCrashLocked(app);
7628 }
7629
Dan Egnorb7f03672009-12-09 16:22:32 -08007630 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007631 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007633 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007634 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7635 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 startAppProblemLocked(app);
7637 app.stopFreezingAllLocked();
7638 }
7639
7640 /**
7641 * Generate a process error record, suitable for attachment to a ProcessRecord.
7642 *
7643 * @param app The ProcessRecord in which the error occurred.
7644 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7645 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007646 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007647 * @param shortMsg Short message describing the crash.
7648 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007649 * @param stackTrace Full crash stack trace, may be null.
7650 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007651 * @return Returns a fully-formed AppErrorStateInfo record.
7652 */
7653 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007654 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007655 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007657 report.condition = condition;
7658 report.processName = app.processName;
7659 report.pid = app.pid;
7660 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007661 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 report.shortMsg = shortMsg;
7663 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007664 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007665
7666 return report;
7667 }
7668
Dan Egnor42471dd2010-01-07 17:25:22 -08007669 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670 synchronized (this) {
7671 app.crashing = false;
7672 app.crashingReport = null;
7673 app.notResponding = false;
7674 app.notRespondingReport = null;
7675 if (app.anrDialog == fromDialog) {
7676 app.anrDialog = null;
7677 }
7678 if (app.waitDialog == fromDialog) {
7679 app.waitDialog = null;
7680 }
7681 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007682 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007683 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007684 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7685 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007686 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 }
7689 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007690
Dan Egnorb7f03672009-12-09 16:22:32 -08007691 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007692 if (mHeadless) {
7693 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7694 return false;
7695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007696 long now = SystemClock.uptimeMillis();
7697
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007698 Long crashTime;
7699 if (!app.isolated) {
7700 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7701 } else {
7702 crashTime = null;
7703 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007704 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007705 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007706 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007708 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007709 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007710 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7711 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007713 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007714 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007715 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716 }
7717 }
7718 if (!app.persistent) {
7719 // We don't want to start this process again until the user
7720 // explicitly does so... but for persistent process, we really
7721 // need to keep it running. If a persistent process is actually
7722 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007723 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007724 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007725 if (!app.isolated) {
7726 // XXX We don't have a way to mark isolated processes
7727 // as bad, since they don't have a peristent identity.
7728 mBadProcesses.put(app.info.processName, app.uid, now);
7729 mProcessCrashTimes.remove(app.info.processName, app.uid);
7730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007731 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007732 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007733 // Don't let services in this process be restarted and potentially
7734 // annoy the user repeatedly. Unless it is persistent, since those
7735 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007736 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007737 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 return false;
7739 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007740 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007741 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007742 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007743 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007744 // If the top running activity is from this crashing
7745 // process, then terminate it to avoid getting in a loop.
7746 Slog.w(TAG, " Force finishing activity "
7747 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007748 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007749 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007750 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007751 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007752 // stopped, to avoid a situation where one will get
7753 // re-start our crashing activity once it gets resumed again.
7754 index--;
7755 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007756 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007757 if (r.state == ActivityState.RESUMED
7758 || r.state == ActivityState.PAUSING
7759 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007760 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007761 Slog.w(TAG, " Force finishing activity "
7762 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007763 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007764 Activity.RESULT_CANCELED, null, "crashed");
7765 }
7766 }
7767 }
7768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007769 }
7770
7771 // Bump up the crash count of any services currently running in the proc.
7772 if (app.services.size() != 0) {
7773 // Any services running in the application need to be placed
7774 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007775 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007777 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007778 sr.crashCount++;
7779 }
7780 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007781
7782 // If the crashing process is what we consider to be the "home process" and it has been
7783 // replaced by a third-party app, clear the package preferred activities from packages
7784 // with a home activity running in the process to prevent a repeatedly crashing app
7785 // from blocking the user to manually clear the list.
7786 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7787 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7788 Iterator it = mHomeProcess.activities.iterator();
7789 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007790 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007791 if (r.isHomeActivity) {
7792 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7793 try {
7794 ActivityThread.getPackageManager()
7795 .clearPackagePreferredActivities(r.packageName);
7796 } catch (RemoteException c) {
7797 // pm is in same process, this will never happen.
7798 }
7799 }
7800 }
7801 }
7802
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007803 if (!app.isolated) {
7804 // XXX Can't keep track of crash times for isolated processes,
7805 // because they don't have a perisistent identity.
7806 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7807 }
7808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 return true;
7810 }
7811
7812 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007813 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7814 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 skipCurrentReceiverLocked(app);
7816 }
7817
7818 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007819 for (BroadcastQueue queue : mBroadcastQueues) {
7820 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007821 }
7822 }
7823
Dan Egnor60d87622009-12-16 16:32:58 -08007824 /**
7825 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7826 * The application process will exit immediately after this call returns.
7827 * @param app object of the crashing app, null for the system server
7828 * @param crashInfo describing the exception
7829 */
7830 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007831 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007832 final String processName = app == null ? "system_server"
7833 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007834
7835 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007836 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007837 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007838 crashInfo.exceptionClassName,
7839 crashInfo.exceptionMessage,
7840 crashInfo.throwFileName,
7841 crashInfo.throwLineNumber);
7842
Jeff Sharkeya353d262011-10-28 11:12:06 -07007843 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007844
7845 crashApplication(r, crashInfo);
7846 }
7847
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007848 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007849 IBinder app,
7850 int violationMask,
7851 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007852 ProcessRecord r = findAppProcess(app, "StrictMode");
7853 if (r == null) {
7854 return;
7855 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007856
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007857 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007858 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007859 boolean logIt = true;
7860 synchronized (mAlreadyLoggedViolatedStacks) {
7861 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7862 logIt = false;
7863 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007864 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007865 // the relative pain numbers, without logging all
7866 // the stack traces repeatedly. We'd want to do
7867 // likewise in the client code, which also does
7868 // dup suppression, before the Binder call.
7869 } else {
7870 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7871 mAlreadyLoggedViolatedStacks.clear();
7872 }
7873 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7874 }
7875 }
7876 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007877 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007878 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007879 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007880
7881 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7882 AppErrorResult result = new AppErrorResult();
7883 synchronized (this) {
7884 final long origId = Binder.clearCallingIdentity();
7885
7886 Message msg = Message.obtain();
7887 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7888 HashMap<String, Object> data = new HashMap<String, Object>();
7889 data.put("result", result);
7890 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007891 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007892 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007893 msg.obj = data;
7894 mHandler.sendMessage(msg);
7895
7896 Binder.restoreCallingIdentity(origId);
7897 }
7898 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007899 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007900 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007901 }
7902
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007903 // Depending on the policy in effect, there could be a bunch of
7904 // these in quick succession so we try to batch these together to
7905 // minimize disk writes, number of dropbox entries, and maximize
7906 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007907 private void logStrictModeViolationToDropBox(
7908 ProcessRecord process,
7909 StrictMode.ViolationInfo info) {
7910 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007911 return;
7912 }
7913 final boolean isSystemApp = process == null ||
7914 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7915 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007916 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007917 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
7918 final DropBoxManager dbox = (DropBoxManager)
7919 mContext.getSystemService(Context.DROPBOX_SERVICE);
7920
7921 // Exit early if the dropbox isn't configured to accept this report type.
7922 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
7923
7924 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007925 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007926 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
7927 synchronized (sb) {
7928 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007929 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007930 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
7931 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007932 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
7933 if (info.violationNumThisLoop != 0) {
7934 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
7935 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07007936 if (info.numAnimationsRunning != 0) {
7937 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
7938 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07007939 if (info.broadcastIntentAction != null) {
7940 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
7941 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007942 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007943 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007944 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08007945 if (info.numInstances != -1) {
7946 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
7947 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08007948 if (info.tags != null) {
7949 for (String tag : info.tags) {
7950 sb.append("Span-Tag: ").append(tag).append("\n");
7951 }
7952 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007953 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007954 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
7955 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007956 }
7957 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007958
7959 // Only buffer up to ~64k. Various logging bits truncate
7960 // things at 128k.
7961 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007962 }
7963
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007964 // Flush immediately if the buffer's grown too large, or this
7965 // is a non-system app. Non-system apps are isolated with a
7966 // different tag & policy and not batched.
7967 //
7968 // Batching is useful during internal testing with
7969 // StrictMode settings turned up high. Without batching,
7970 // thousands of separate files could be created on boot.
7971 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007972 new Thread("Error dump: " + dropboxTag) {
7973 @Override
7974 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007975 String report;
7976 synchronized (sb) {
7977 report = sb.toString();
7978 sb.delete(0, sb.length());
7979 sb.trimToSize();
7980 }
7981 if (report.length() != 0) {
7982 dbox.addText(dropboxTag, report);
7983 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007984 }
7985 }.start();
7986 return;
7987 }
7988
7989 // System app batching:
7990 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07007991 // An existing dropbox-writing thread is outstanding, so
7992 // we don't need to start it up. The existing thread will
7993 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007994 return;
7995 }
7996
7997 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
7998 // (After this point, we shouldn't access AMS internal data structures.)
7999 new Thread("Error dump: " + dropboxTag) {
8000 @Override
8001 public void run() {
8002 // 5 second sleep to let stacks arrive and be batched together
8003 try {
8004 Thread.sleep(5000); // 5 seconds
8005 } catch (InterruptedException e) {}
8006
8007 String errorReport;
8008 synchronized (mStrictModeBuffer) {
8009 errorReport = mStrictModeBuffer.toString();
8010 if (errorReport.length() == 0) {
8011 return;
8012 }
8013 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8014 mStrictModeBuffer.trimToSize();
8015 }
8016 dbox.addText(dropboxTag, errorReport);
8017 }
8018 }.start();
8019 }
8020
Dan Egnor60d87622009-12-16 16:32:58 -08008021 /**
8022 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8023 * @param app object of the crashing app, null for the system server
8024 * @param tag reported by the caller
8025 * @param crashInfo describing the context of the error
8026 * @return true if the process should exit immediately (WTF is fatal)
8027 */
8028 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008029 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008030 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008031 final String processName = app == null ? "system_server"
8032 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008033
8034 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008035 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008036 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008037 tag, crashInfo.exceptionMessage);
8038
Jeff Sharkeya353d262011-10-28 11:12:06 -07008039 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008040
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008041 if (r != null && r.pid != Process.myPid() &&
8042 Settings.Secure.getInt(mContext.getContentResolver(),
8043 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008044 crashApplication(r, crashInfo);
8045 return true;
8046 } else {
8047 return false;
8048 }
8049 }
8050
8051 /**
8052 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8053 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8054 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008055 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008056 if (app == null) {
8057 return null;
8058 }
8059
8060 synchronized (this) {
8061 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8062 final int NA = apps.size();
8063 for (int ia=0; ia<NA; ia++) {
8064 ProcessRecord p = apps.valueAt(ia);
8065 if (p.thread != null && p.thread.asBinder() == app) {
8066 return p;
8067 }
8068 }
8069 }
8070
Dianne Hackborncb44d962011-03-10 17:02:27 -08008071 Slog.w(TAG, "Can't find mystery application for " + reason
8072 + " from pid=" + Binder.getCallingPid()
8073 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008074 return null;
8075 }
8076 }
8077
8078 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008079 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8080 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008081 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008082 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8083 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008084 // Watchdog thread ends up invoking this function (with
8085 // a null ProcessRecord) to add the stack file to dropbox.
8086 // Do not acquire a lock on this (am) in such cases, as it
8087 // could cause a potential deadlock, if and when watchdog
8088 // is invoked due to unavailability of lock on am and it
8089 // would prevent watchdog from killing system_server.
8090 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008091 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008092 return;
8093 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008094 // Note: ProcessRecord 'process' is guarded by the service
8095 // instance. (notably process.pkgList, which could otherwise change
8096 // concurrently during execution of this method)
8097 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008098 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008099 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008100 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008101 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8102 for (String pkg : process.pkgList) {
8103 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008104 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008105 PackageInfo pi = pm.getPackageInfo(pkg, 0, 0);
Dan Egnora455d192010-03-12 08:52:28 -08008106 if (pi != null) {
8107 sb.append(" v").append(pi.versionCode);
8108 if (pi.versionName != null) {
8109 sb.append(" (").append(pi.versionName).append(")");
8110 }
8111 }
8112 } catch (RemoteException e) {
8113 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008114 }
Dan Egnora455d192010-03-12 08:52:28 -08008115 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008116 }
Dan Egnora455d192010-03-12 08:52:28 -08008117 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008118 }
8119
8120 private static String processClass(ProcessRecord process) {
8121 if (process == null || process.pid == MY_PID) {
8122 return "system_server";
8123 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8124 return "system_app";
8125 } else {
8126 return "data_app";
8127 }
8128 }
8129
8130 /**
8131 * Write a description of an error (crash, WTF, ANR) to the drop box.
8132 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8133 * @param process which caused the error, null means the system server
8134 * @param activity which triggered the error, null if unknown
8135 * @param parent activity related to the error, null if unknown
8136 * @param subject line related to the error, null if absent
8137 * @param report in long form describing the error, null if absent
8138 * @param logFile to include in the report, null if none
8139 * @param crashInfo giving an application stack trace, null if absent
8140 */
8141 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008142 ProcessRecord process, String processName, ActivityRecord activity,
8143 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008144 final String report, final File logFile,
8145 final ApplicationErrorReport.CrashInfo crashInfo) {
8146 // NOTE -- this must never acquire the ActivityManagerService lock,
8147 // otherwise the watchdog may be prevented from resetting the system.
8148
8149 final String dropboxTag = processClass(process) + "_" + eventType;
8150 final DropBoxManager dbox = (DropBoxManager)
8151 mContext.getSystemService(Context.DROPBOX_SERVICE);
8152
8153 // Exit early if the dropbox isn't configured to accept this report type.
8154 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8155
8156 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008157 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008158 if (activity != null) {
8159 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8160 }
8161 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8162 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8163 }
8164 if (parent != null && parent != activity) {
8165 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8166 }
8167 if (subject != null) {
8168 sb.append("Subject: ").append(subject).append("\n");
8169 }
8170 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008171 if (Debug.isDebuggerConnected()) {
8172 sb.append("Debugger: Connected\n");
8173 }
Dan Egnora455d192010-03-12 08:52:28 -08008174 sb.append("\n");
8175
8176 // Do the rest in a worker thread to avoid blocking the caller on I/O
8177 // (After this point, we shouldn't access AMS internal data structures.)
8178 Thread worker = new Thread("Error dump: " + dropboxTag) {
8179 @Override
8180 public void run() {
8181 if (report != null) {
8182 sb.append(report);
8183 }
8184 if (logFile != null) {
8185 try {
8186 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8187 } catch (IOException e) {
8188 Slog.e(TAG, "Error reading " + logFile, e);
8189 }
8190 }
8191 if (crashInfo != null && crashInfo.stackTrace != null) {
8192 sb.append(crashInfo.stackTrace);
8193 }
8194
8195 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8196 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8197 if (lines > 0) {
8198 sb.append("\n");
8199
8200 // Merge several logcat streams, and take the last N lines
8201 InputStreamReader input = null;
8202 try {
8203 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8204 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8205 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8206
8207 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8208 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8209 input = new InputStreamReader(logcat.getInputStream());
8210
8211 int num;
8212 char[] buf = new char[8192];
8213 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8214 } catch (IOException e) {
8215 Slog.e(TAG, "Error running logcat", e);
8216 } finally {
8217 if (input != null) try { input.close(); } catch (IOException e) {}
8218 }
8219 }
8220
8221 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008222 }
Dan Egnora455d192010-03-12 08:52:28 -08008223 };
8224
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008225 if (process == null) {
8226 // If process is null, we are being called from some internal code
8227 // and may be about to die -- run this synchronously.
8228 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008229 } else {
8230 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008231 }
8232 }
8233
8234 /**
8235 * Bring up the "unexpected error" dialog box for a crashing app.
8236 * Deal with edge cases (intercepts from instrumented applications,
8237 * ActivityController, error intent receivers, that sort of thing).
8238 * @param r the application crashing
8239 * @param crashInfo describing the failure
8240 */
8241 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008242 long timeMillis = System.currentTimeMillis();
8243 String shortMsg = crashInfo.exceptionClassName;
8244 String longMsg = crashInfo.exceptionMessage;
8245 String stackTrace = crashInfo.stackTrace;
8246 if (shortMsg != null && longMsg != null) {
8247 longMsg = shortMsg + ": " + longMsg;
8248 } else if (shortMsg != null) {
8249 longMsg = shortMsg;
8250 }
8251
Dan Egnor60d87622009-12-16 16:32:58 -08008252 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008253 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008254 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008255 try {
8256 String name = r != null ? r.processName : null;
8257 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008258 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008259 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008260 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008261 + " at watcher's request");
8262 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008263 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008264 }
8265 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008266 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008267 }
8268 }
8269
8270 final long origId = Binder.clearCallingIdentity();
8271
8272 // If this process is running instrumentation, finish it.
8273 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008274 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008275 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008276 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8277 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008278 Bundle info = new Bundle();
8279 info.putString("shortMsg", shortMsg);
8280 info.putString("longMsg", longMsg);
8281 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8282 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008283 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 }
8285
Dan Egnor60d87622009-12-16 16:32:58 -08008286 // If we can't identify the process or it's already exceeded its crash quota,
8287 // quit right away without showing a crash dialog.
8288 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008289 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008290 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008291 }
8292
8293 Message msg = Message.obtain();
8294 msg.what = SHOW_ERROR_MSG;
8295 HashMap data = new HashMap();
8296 data.put("result", result);
8297 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008298 msg.obj = data;
8299 mHandler.sendMessage(msg);
8300
8301 Binder.restoreCallingIdentity(origId);
8302 }
8303
8304 int res = result.get();
8305
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008306 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008307 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008308 if (r != null && !r.isolated) {
8309 // XXX Can't keep track of crash time for isolated processes,
8310 // since they don't have a persistent identity.
8311 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008312 SystemClock.uptimeMillis());
8313 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008314 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008315 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008316 }
8317 }
8318
8319 if (appErrorIntent != null) {
8320 try {
8321 mContext.startActivity(appErrorIntent);
8322 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008323 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008326 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008327
8328 Intent createAppErrorIntentLocked(ProcessRecord r,
8329 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8330 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008331 if (report == null) {
8332 return null;
8333 }
8334 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8335 result.setComponent(r.errorReportReceiver);
8336 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8337 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8338 return result;
8339 }
8340
Dan Egnorb7f03672009-12-09 16:22:32 -08008341 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8342 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008343 if (r.errorReportReceiver == null) {
8344 return null;
8345 }
8346
8347 if (!r.crashing && !r.notResponding) {
8348 return null;
8349 }
8350
Dan Egnorb7f03672009-12-09 16:22:32 -08008351 ApplicationErrorReport report = new ApplicationErrorReport();
8352 report.packageName = r.info.packageName;
8353 report.installerPackageName = r.errorReportReceiver.getPackageName();
8354 report.processName = r.processName;
8355 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008356 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008357
Dan Egnorb7f03672009-12-09 16:22:32 -08008358 if (r.crashing) {
8359 report.type = ApplicationErrorReport.TYPE_CRASH;
8360 report.crashInfo = crashInfo;
8361 } else if (r.notResponding) {
8362 report.type = ApplicationErrorReport.TYPE_ANR;
8363 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008364
Dan Egnorb7f03672009-12-09 16:22:32 -08008365 report.anrInfo.activity = r.notRespondingReport.tag;
8366 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8367 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008368 }
8369
Dan Egnorb7f03672009-12-09 16:22:32 -08008370 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008371 }
8372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008373 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008374 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008375 // assume our apps are happy - lazy create the list
8376 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8377
8378 synchronized (this) {
8379
8380 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008381 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8382 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008383 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8384 // This one's in trouble, so we'll generate a report for it
8385 // crashes are higher priority (in case there's a crash *and* an anr)
8386 ActivityManager.ProcessErrorStateInfo report = null;
8387 if (app.crashing) {
8388 report = app.crashingReport;
8389 } else if (app.notResponding) {
8390 report = app.notRespondingReport;
8391 }
8392
8393 if (report != null) {
8394 if (errList == null) {
8395 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8396 }
8397 errList.add(report);
8398 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008399 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008400 " crashing = " + app.crashing +
8401 " notResponding = " + app.notResponding);
8402 }
8403 }
8404 }
8405 }
8406
8407 return errList;
8408 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008409
8410 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008411 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008412 if (currApp != null) {
8413 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8414 }
8415 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008416 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8417 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008418 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8419 if (currApp != null) {
8420 currApp.lru = 0;
8421 }
8422 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008423 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008424 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8425 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8426 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8427 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8428 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8429 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8430 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8431 } else {
8432 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8433 }
8434 }
8435
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008436 private void fillInProcMemInfo(ProcessRecord app,
8437 ActivityManager.RunningAppProcessInfo outInfo) {
8438 outInfo.pid = app.pid;
8439 outInfo.uid = app.info.uid;
8440 if (mHeavyWeightProcess == app) {
8441 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8442 }
8443 if (app.persistent) {
8444 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8445 }
8446 outInfo.lastTrimLevel = app.trimMemoryLevel;
8447 int adj = app.curAdj;
8448 outInfo.importance = oomAdjToImportance(adj, outInfo);
8449 outInfo.importanceReasonCode = app.adjTypeCode;
8450 }
8451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008452 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008453 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008454 // Lazy instantiation of list
8455 List<ActivityManager.RunningAppProcessInfo> runList = null;
8456 synchronized (this) {
8457 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008458 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8459 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008460 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8461 // Generate process state info for running application
8462 ActivityManager.RunningAppProcessInfo currApp =
8463 new ActivityManager.RunningAppProcessInfo(app.processName,
8464 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008465 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008466 if (app.adjSource instanceof ProcessRecord) {
8467 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008468 currApp.importanceReasonImportance = oomAdjToImportance(
8469 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008470 } else if (app.adjSource instanceof ActivityRecord) {
8471 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008472 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8473 }
8474 if (app.adjTarget instanceof ComponentName) {
8475 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8476 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008477 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008478 // + " lru=" + currApp.lru);
8479 if (runList == null) {
8480 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8481 }
8482 runList.add(currApp);
8483 }
8484 }
8485 }
8486 return runList;
8487 }
8488
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008489 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008490 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008491 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8492 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8493 if (runningApps != null && runningApps.size() > 0) {
8494 Set<String> extList = new HashSet<String>();
8495 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8496 if (app.pkgList != null) {
8497 for (String pkg : app.pkgList) {
8498 extList.add(pkg);
8499 }
8500 }
8501 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008502 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008503 for (String pkg : extList) {
8504 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07008505 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserId.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008506 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8507 retList.add(info);
8508 }
8509 } catch (RemoteException e) {
8510 }
8511 }
8512 }
8513 return retList;
8514 }
8515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008517 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8518 enforceNotIsolatedCaller("getMyMemoryState");
8519 synchronized (this) {
8520 ProcessRecord proc;
8521 synchronized (mPidsSelfLocked) {
8522 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8523 }
8524 fillInProcMemInfo(proc, outInfo);
8525 }
8526 }
8527
8528 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008529 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008530 if (checkCallingPermission(android.Manifest.permission.DUMP)
8531 != PackageManager.PERMISSION_GRANTED) {
8532 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8533 + Binder.getCallingPid()
8534 + ", uid=" + Binder.getCallingUid()
8535 + " without permission "
8536 + android.Manifest.permission.DUMP);
8537 return;
8538 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008539
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008540 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008541 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008542 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008543
8544 int opti = 0;
8545 while (opti < args.length) {
8546 String opt = args[opti];
8547 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8548 break;
8549 }
8550 opti++;
8551 if ("-a".equals(opt)) {
8552 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008553 } else if ("-c".equals(opt)) {
8554 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008555 } else if ("-h".equals(opt)) {
8556 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008557 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008558 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008559 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008560 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8561 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8562 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008563 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008564 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008565 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008566 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008567 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008568 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008569 pw.println(" all: dump all activities");
8570 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008571 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008572 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8573 pw.println(" a partial substring in a component name, a");
8574 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008575 pw.println(" -a: include all available server state.");
8576 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008578 } else {
8579 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008580 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008581 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008582
8583 long origId = Binder.clearCallingIdentity();
8584 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008585 // Is the caller requesting to dump a particular piece of data?
8586 if (opti < args.length) {
8587 String cmd = args[opti];
8588 opti++;
8589 if ("activities".equals(cmd) || "a".equals(cmd)) {
8590 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008591 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008593 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008594 String[] newArgs;
8595 String name;
8596 if (opti >= args.length) {
8597 name = null;
8598 newArgs = EMPTY_STRING_ARRAY;
8599 } else {
8600 name = args[opti];
8601 opti++;
8602 newArgs = new String[args.length - opti];
8603 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8604 args.length - opti);
8605 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008606 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008607 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008608 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008609 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008610 String[] newArgs;
8611 String name;
8612 if (opti >= args.length) {
8613 name = null;
8614 newArgs = EMPTY_STRING_ARRAY;
8615 } else {
8616 name = args[opti];
8617 opti++;
8618 newArgs = new String[args.length - opti];
8619 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8620 args.length - opti);
8621 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008622 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008623 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008624 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008625 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008626 String[] newArgs;
8627 String name;
8628 if (opti >= args.length) {
8629 name = null;
8630 newArgs = EMPTY_STRING_ARRAY;
8631 } else {
8632 name = args[opti];
8633 opti++;
8634 newArgs = new String[args.length - opti];
8635 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8636 args.length - opti);
8637 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008638 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008639 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008640 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008641 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8642 synchronized (this) {
8643 dumpOomLocked(fd, pw, args, opti, true);
8644 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008645 } else if ("provider".equals(cmd)) {
8646 String[] newArgs;
8647 String name;
8648 if (opti >= args.length) {
8649 name = null;
8650 newArgs = EMPTY_STRING_ARRAY;
8651 } else {
8652 name = args[opti];
8653 opti++;
8654 newArgs = new String[args.length - opti];
8655 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8656 }
8657 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8658 pw.println("No providers match: " + name);
8659 pw.println("Use -h for help.");
8660 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008661 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8662 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008663 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008664 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008665 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008666 String[] newArgs;
8667 String name;
8668 if (opti >= args.length) {
8669 name = null;
8670 newArgs = EMPTY_STRING_ARRAY;
8671 } else {
8672 name = args[opti];
8673 opti++;
8674 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008675 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8676 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008677 }
8678 if (!dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
8679 pw.println("No services match: " + name);
8680 pw.println("Use -h for help.");
8681 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008682 } else if ("package".equals(cmd)) {
8683 String[] newArgs;
8684 if (opti >= args.length) {
8685 pw.println("package: no package name specified");
8686 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008687 } else {
8688 dumpPackage = args[opti];
8689 opti++;
8690 newArgs = new String[args.length - opti];
8691 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8692 args.length - opti);
8693 args = newArgs;
8694 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008695 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008696 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008697 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8698 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008699 dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008700 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008701 } else {
8702 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008703 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8704 pw.println("Bad activity command, or no activities match: " + cmd);
8705 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008706 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008707 }
8708 if (!more) {
8709 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008710 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008711 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008712 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008713
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008714 // No piece of data specified, dump everything.
8715 synchronized (this) {
8716 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008717 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008718 if (needSep) {
8719 pw.println(" ");
8720 }
8721 if (dumpAll) {
8722 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008723 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008724 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008725 if (needSep) {
8726 pw.println(" ");
8727 }
8728 if (dumpAll) {
8729 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008730 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008731 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008732 if (needSep) {
8733 pw.println(" ");
8734 }
8735 if (dumpAll) {
8736 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008737 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008738 needSep = dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008739 if (needSep) {
8740 pw.println(" ");
8741 }
8742 if (dumpAll) {
8743 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008744 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008745 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008746 if (needSep) {
8747 pw.println(" ");
8748 }
8749 if (dumpAll) {
8750 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008751 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008752 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008753 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008754 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008755 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008756
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008757 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008758 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008759 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8760 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008761 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8762 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008763 pw.println(" ");
8764 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008765 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8766 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008767 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008768 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008769 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008770 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008771 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008772 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008773 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008775 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008776 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008777 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008778 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008779 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8780 pw.println(" ");
8781 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008782 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008783 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008784 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008785 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008786 pw.println(" ");
8787 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008788 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008789 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008791
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008792 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008793 if (mMainStack.mPausingActivity != null) {
8794 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008795 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008796 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008797 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008798 if (dumpAll) {
8799 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8800 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008801 pw.println(" mDismissKeyguardOnNextActivity: "
8802 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008804
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008805 if (mRecentTasks.size() > 0) {
8806 pw.println();
8807 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008808
8809 final int N = mRecentTasks.size();
8810 for (int i=0; i<N; i++) {
8811 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008812 if (dumpPackage != null) {
8813 if (tr.realActivity == null ||
8814 !dumpPackage.equals(tr.realActivity)) {
8815 continue;
8816 }
8817 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008818 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8819 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008820 if (dumpAll) {
8821 mRecentTasks.get(i).dump(pw, " ");
8822 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008823 }
8824 }
8825
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008826 if (dumpAll) {
8827 pw.println(" ");
8828 pw.println(" mCurTask: " + mCurTask);
8829 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008830
8831 return true;
8832 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008833
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008834 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008835 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008836 boolean needSep = false;
8837 int numPers = 0;
8838
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008839 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8840
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008841 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008842 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8843 final int NA = procs.size();
8844 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008845 ProcessRecord r = procs.valueAt(ia);
8846 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8847 continue;
8848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008849 if (!needSep) {
8850 pw.println(" All known processes:");
8851 needSep = true;
8852 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008853 pw.print(r.persistent ? " *PERS*" : " *APP*");
8854 pw.print(" UID "); pw.print(procs.keyAt(ia));
8855 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008856 r.dump(pw, " ");
8857 if (r.persistent) {
8858 numPers++;
8859 }
8860 }
8861 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008862 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008863
8864 if (mIsolatedProcesses.size() > 0) {
8865 if (needSep) pw.println(" ");
8866 needSep = true;
8867 pw.println(" Isolated process list (sorted by uid):");
8868 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8869 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8870 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8871 continue;
8872 }
8873 pw.println(String.format("%sIsolated #%2d: %s",
8874 " ", i, r.toString()));
8875 }
8876 }
8877
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008878 if (mLruProcesses.size() > 0) {
8879 if (needSep) pw.println(" ");
8880 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008881 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008882 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008883 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008884 needSep = true;
8885 }
8886
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008887 if (dumpAll) {
8888 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008889 boolean printed = false;
8890 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8891 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8892 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8893 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008894 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008895 if (!printed) {
8896 if (needSep) pw.println(" ");
8897 needSep = true;
8898 pw.println(" PID mappings:");
8899 printed = true;
8900 }
8901 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
8902 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008903 }
8904 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008905 }
8906
8907 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008908 synchronized (mPidsSelfLocked) {
8909 boolean printed = false;
8910 for (int i=0; i<mForegroundProcesses.size(); i++) {
8911 ProcessRecord r = mPidsSelfLocked.get(
8912 mForegroundProcesses.valueAt(i).pid);
8913 if (dumpPackage != null && (r == null
8914 || !dumpPackage.equals(r.info.packageName))) {
8915 continue;
8916 }
8917 if (!printed) {
8918 if (needSep) pw.println(" ");
8919 needSep = true;
8920 pw.println(" Foreground Processes:");
8921 printed = true;
8922 }
8923 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
8924 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
8925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008926 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008927 }
8928
8929 if (mPersistentStartingProcesses.size() > 0) {
8930 if (needSep) pw.println(" ");
8931 needSep = true;
8932 pw.println(" Persisent processes that are starting:");
8933 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008934 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008937 if (mRemovedProcesses.size() > 0) {
8938 if (needSep) pw.println(" ");
8939 needSep = true;
8940 pw.println(" Processes that are being removed:");
8941 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008942 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008943 }
8944
8945 if (mProcessesOnHold.size() > 0) {
8946 if (needSep) pw.println(" ");
8947 needSep = true;
8948 pw.println(" Processes that are on old until the system is ready:");
8949 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008950 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008953 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008954
8955 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008956 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008957 long now = SystemClock.uptimeMillis();
8958 for (Map.Entry<String, SparseArray<Long>> procs
8959 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008960 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008961 SparseArray<Long> uids = procs.getValue();
8962 final int N = uids.size();
8963 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008964 int puid = uids.keyAt(i);
8965 ProcessRecord r = mProcessNames.get(pname, puid);
8966 if (dumpPackage != null && (r == null
8967 || !dumpPackage.equals(r.info.packageName))) {
8968 continue;
8969 }
8970 if (!printed) {
8971 if (needSep) pw.println(" ");
8972 needSep = true;
8973 pw.println(" Time since processes crashed:");
8974 printed = true;
8975 }
8976 pw.print(" Process "); pw.print(pname);
8977 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008978 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008979 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
8980 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07008981 }
8982 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008984
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008985 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008986 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008987 for (Map.Entry<String, SparseArray<Long>> procs
8988 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008989 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008990 SparseArray<Long> uids = procs.getValue();
8991 final int N = uids.size();
8992 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008993 int puid = uids.keyAt(i);
8994 ProcessRecord r = mProcessNames.get(pname, puid);
8995 if (dumpPackage != null && (r == null
8996 || !dumpPackage.equals(r.info.packageName))) {
8997 continue;
8998 }
8999 if (!printed) {
9000 if (needSep) pw.println(" ");
9001 needSep = true;
9002 pw.println(" Bad processes:");
9003 }
9004 pw.print(" Bad process "); pw.print(pname);
9005 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009006 pw.print(": crashed at time ");
9007 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009008 }
9009 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009011
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009012 pw.println();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009013 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009014 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009015 if (dumpAll) {
9016 StringBuilder sb = new StringBuilder(128);
9017 sb.append(" mPreviousProcessVisibleTime: ");
9018 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9019 pw.println(sb);
9020 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009021 if (mHeavyWeightProcess != null) {
9022 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9023 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009024 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009025 if (dumpAll) {
9026 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009027 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009028 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009029 for (Map.Entry<String, Integer> entry
9030 : mCompatModePackages.getPackages().entrySet()) {
9031 String pkg = entry.getKey();
9032 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009033 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9034 continue;
9035 }
9036 if (!printed) {
9037 pw.println(" mScreenCompatPackages:");
9038 printed = true;
9039 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009040 pw.print(" "); pw.print(pkg); pw.print(": ");
9041 pw.print(mode); pw.println();
9042 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009043 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009044 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009045 if (mSleeping || mWentToSleep || mLockScreenShown) {
9046 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9047 + " mLockScreenShown " + mLockScreenShown);
9048 }
9049 if (mShuttingDown) {
9050 pw.println(" mShuttingDown=" + mShuttingDown);
9051 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009052 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9053 || mOrigWaitForDebugger) {
9054 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9055 + " mDebugTransient=" + mDebugTransient
9056 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9057 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009058 if (mOpenGlTraceApp != null) {
9059 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9060 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009061 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9062 || mProfileFd != null) {
9063 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9064 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9065 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9066 + mAutoStopProfiler);
9067 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009068 if (mAlwaysFinishActivities || mController != null) {
9069 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9070 + " mController=" + mController);
9071 }
9072 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009073 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009074 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009075 + " mProcessesReady=" + mProcessesReady
9076 + " mSystemReady=" + mSystemReady);
9077 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078 + " mBooted=" + mBooted
9079 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009080 pw.print(" mLastPowerCheckRealtime=");
9081 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9082 pw.println("");
9083 pw.print(" mLastPowerCheckUptime=");
9084 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9085 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009086 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9087 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009088 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009089 pw.println(" mNumServiceProcs=" + mNumServiceProcs
9090 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009092
9093 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009094 }
9095
Dianne Hackborn287952c2010-09-22 22:34:31 -07009096 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009097 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009098 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009099 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009100 long now = SystemClock.uptimeMillis();
9101 for (int i=0; i<mProcessesToGc.size(); i++) {
9102 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009103 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9104 continue;
9105 }
9106 if (!printed) {
9107 if (needSep) pw.println(" ");
9108 needSep = true;
9109 pw.println(" Processes that are waiting to GC:");
9110 printed = true;
9111 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009112 pw.print(" Process "); pw.println(proc);
9113 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9114 pw.print(", last gced=");
9115 pw.print(now-proc.lastRequestedGc);
9116 pw.print(" ms ago, last lowMem=");
9117 pw.print(now-proc.lastLowMemory);
9118 pw.println(" ms ago");
9119
9120 }
9121 }
9122 return needSep;
9123 }
9124
9125 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9126 int opti, boolean dumpAll) {
9127 boolean needSep = false;
9128
9129 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009130 if (needSep) pw.println(" ");
9131 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009132 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009133 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009134 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009135 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9136 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9137 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9138 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9139 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009140 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009141 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009142 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009143 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009144 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009145 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009146
9147 if (needSep) pw.println(" ");
9148 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009149 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009150 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009151 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009152 needSep = true;
9153 }
9154
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009155 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009156
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009157 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009158 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009159 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009160 if (mHeavyWeightProcess != null) {
9161 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9162 }
9163
9164 return true;
9165 }
9166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009167 /**
9168 * There are three ways to call this:
9169 * - no service specified: dump all the services
9170 * - a flattened component name that matched an existing service was specified as the
9171 * first arg: dump that one service
9172 * - the first arg isn't the flattened component name of an existing service:
9173 * dump all services whose component contains the first arg as a substring
9174 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009175 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9176 int opti, boolean dumpAll) {
9177 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009178
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009179 if ("all".equals(name)) {
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009180 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009181 try {
9182 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9183 for (UserInfo user : users) {
9184 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9185 services.add(r1);
9186 }
9187 }
9188 } catch (RemoteException re) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009189 }
9190 }
9191 } else {
9192 ComponentName componentName = name != null
9193 ? ComponentName.unflattenFromString(name) : null;
9194 int objectId = 0;
9195 if (componentName == null) {
9196 // Not a '/' separated full component name; maybe an object ID?
9197 try {
9198 objectId = Integer.parseInt(name, 16);
9199 name = null;
9200 componentName = null;
9201 } catch (RuntimeException e) {
9202 }
9203 }
9204
9205 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07009206 try {
9207 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9208 for (UserInfo user : users) {
9209 for (ServiceRecord r1 : mServiceMap.getAllServices(user.id)) {
9210 if (componentName != null) {
9211 if (r1.name.equals(componentName)) {
9212 services.add(r1);
9213 }
9214 } else if (name != null) {
9215 if (r1.name.flattenToString().contains(name)) {
9216 services.add(r1);
9217 }
9218 } else if (System.identityHashCode(r1) == objectId) {
9219 services.add(r1);
9220 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009221 }
Dianne Hackborn14bfa392010-07-24 19:58:06 -07009222 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009223 } catch (RemoteException re) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009224 }
9225 }
9226 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009227
9228 if (services.size() <= 0) {
9229 return false;
9230 }
9231
9232 boolean needSep = false;
9233 for (int i=0; i<services.size(); i++) {
9234 if (needSep) {
9235 pw.println();
9236 }
9237 needSep = true;
9238 dumpService("", fd, pw, services.get(i), args, dumpAll);
9239 }
9240 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009241 }
9242
9243 /**
9244 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
9245 * there is a thread associated with the service.
9246 */
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009247 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
9248 final ServiceRecord r, String[] args, boolean dumpAll) {
9249 String innerPrefix = prefix + " ";
9250 synchronized (this) {
9251 pw.print(prefix); pw.print("SERVICE ");
9252 pw.print(r.shortName); pw.print(" ");
9253 pw.print(Integer.toHexString(System.identityHashCode(r)));
9254 pw.print(" pid=");
9255 if (r.app != null) pw.println(r.app.pid);
9256 else pw.println("(not running)");
9257 if (dumpAll) {
9258 r.dump(pw, innerPrefix);
9259 }
9260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009261 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009262 pw.print(prefix); pw.println(" Client:");
9263 pw.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009264 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009265 TransferPipe tp = new TransferPipe();
9266 try {
9267 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
9268 tp.setBufferPrefix(prefix + " ");
9269 tp.go(fd);
9270 } finally {
9271 tp.kill();
9272 }
9273 } catch (IOException e) {
9274 pw.println(prefix + " Failure while dumping the service: " + e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009275 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009276 pw.println(prefix + " Got a RemoteException while dumping the service");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009277 }
9278 }
9279 }
9280
Marco Nelissen18cb2872011-11-15 11:19:53 -08009281 /**
9282 * There are three ways to call this:
9283 * - no provider specified: dump all the providers
9284 * - a flattened component name that matched an existing provider was specified as the
9285 * first arg: dump that one provider
9286 * - the first arg isn't the flattened component name of an existing provider:
9287 * dump all providers whose component contains the first arg as a substring
9288 */
9289 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9290 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009291 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009292 }
9293
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009294 static class ItemMatcher {
9295 ArrayList<ComponentName> components;
9296 ArrayList<String> strings;
9297 ArrayList<Integer> objects;
9298 boolean all;
9299
9300 ItemMatcher() {
9301 all = true;
9302 }
9303
9304 void build(String name) {
9305 ComponentName componentName = ComponentName.unflattenFromString(name);
9306 if (componentName != null) {
9307 if (components == null) {
9308 components = new ArrayList<ComponentName>();
9309 }
9310 components.add(componentName);
9311 all = false;
9312 } else {
9313 int objectId = 0;
9314 // Not a '/' separated full component name; maybe an object ID?
9315 try {
9316 objectId = Integer.parseInt(name, 16);
9317 if (objects == null) {
9318 objects = new ArrayList<Integer>();
9319 }
9320 objects.add(objectId);
9321 all = false;
9322 } catch (RuntimeException e) {
9323 // Not an integer; just do string match.
9324 if (strings == null) {
9325 strings = new ArrayList<String>();
9326 }
9327 strings.add(name);
9328 all = false;
9329 }
9330 }
9331 }
9332
9333 int build(String[] args, int opti) {
9334 for (; opti<args.length; opti++) {
9335 String name = args[opti];
9336 if ("--".equals(name)) {
9337 return opti+1;
9338 }
9339 build(name);
9340 }
9341 return opti;
9342 }
9343
9344 boolean match(Object object, ComponentName comp) {
9345 if (all) {
9346 return true;
9347 }
9348 if (components != null) {
9349 for (int i=0; i<components.size(); i++) {
9350 if (components.get(i).equals(comp)) {
9351 return true;
9352 }
9353 }
9354 }
9355 if (objects != null) {
9356 for (int i=0; i<objects.size(); i++) {
9357 if (System.identityHashCode(object) == objects.get(i)) {
9358 return true;
9359 }
9360 }
9361 }
9362 if (strings != null) {
9363 String flat = comp.flattenToString();
9364 for (int i=0; i<strings.size(); i++) {
9365 if (flat.contains(strings.get(i))) {
9366 return true;
9367 }
9368 }
9369 }
9370 return false;
9371 }
9372 }
9373
Dianne Hackborn625ac272010-09-17 18:29:22 -07009374 /**
9375 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009376 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009377 * - the cmd arg isn't the flattened component name of an existing activity:
9378 * dump all activity whose component contains the cmd as a substring
9379 * - A hex number of the ActivityRecord object instance.
9380 */
9381 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9382 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009383 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009384
9385 if ("all".equals(name)) {
9386 synchronized (this) {
9387 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009388 activities.add(r1);
9389 }
9390 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009391 } else if ("top".equals(name)) {
9392 synchronized (this) {
9393 final int N = mMainStack.mHistory.size();
9394 if (N > 0) {
9395 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9396 }
9397 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009398 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009399 ItemMatcher matcher = new ItemMatcher();
9400 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009401
9402 synchronized (this) {
9403 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009404 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009405 activities.add(r1);
9406 }
9407 }
9408 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009409 }
9410
9411 if (activities.size() <= 0) {
9412 return false;
9413 }
9414
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009415 String[] newArgs = new String[args.length - opti];
9416 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9417
Dianne Hackborn30d71892010-12-11 10:37:55 -08009418 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009419 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009420 for (int i=activities.size()-1; i>=0; i--) {
9421 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009422 if (needSep) {
9423 pw.println();
9424 }
9425 needSep = true;
9426 synchronized (this) {
9427 if (lastTask != r.task) {
9428 lastTask = r.task;
9429 pw.print("TASK "); pw.print(lastTask.affinity);
9430 pw.print(" id="); pw.println(lastTask.taskId);
9431 if (dumpAll) {
9432 lastTask.dump(pw, " ");
9433 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009434 }
9435 }
9436 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009437 }
9438 return true;
9439 }
9440
9441 /**
9442 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9443 * there is a thread associated with the activity.
9444 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009445 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009446 final ActivityRecord r, String[] args, boolean dumpAll) {
9447 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009448 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009449 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9450 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9451 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009452 if (r.app != null) pw.println(r.app.pid);
9453 else pw.println("(not running)");
9454 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009455 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009456 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009457 }
9458 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009459 // flush anything that is already in the PrintWriter since the thread is going
9460 // to write to the file descriptor directly
9461 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009462 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009463 TransferPipe tp = new TransferPipe();
9464 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009465 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9466 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009467 tp.go(fd);
9468 } finally {
9469 tp.kill();
9470 }
9471 } catch (IOException e) {
9472 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009473 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009474 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009475 }
9476 }
9477 }
9478
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009479 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009480 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009481 boolean needSep = false;
9482
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009483 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009484 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009485 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009486 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009487 Iterator it = mRegisteredReceivers.values().iterator();
9488 while (it.hasNext()) {
9489 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009490 if (dumpPackage != null && (r.app == null ||
9491 !dumpPackage.equals(r.app.info.packageName))) {
9492 continue;
9493 }
9494 if (!printed) {
9495 pw.println(" Registered Receivers:");
9496 needSep = true;
9497 printed = true;
9498 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009499 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009500 r.dump(pw, " ");
9501 }
9502 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009503
9504 if (mReceiverResolver.dump(pw, needSep ?
9505 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9506 " ", dumpPackage, false)) {
9507 needSep = true;
9508 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009509 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009510
9511 for (BroadcastQueue q : mBroadcastQueues) {
9512 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009514
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009515 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009516
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009517 if (mStickyBroadcasts != null && dumpPackage == null) {
9518 if (needSep) {
9519 pw.println();
9520 }
9521 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009522 pw.println(" Sticky broadcasts:");
9523 StringBuilder sb = new StringBuilder(128);
9524 for (Map.Entry<String, ArrayList<Intent>> ent
9525 : mStickyBroadcasts.entrySet()) {
9526 pw.print(" * Sticky action "); pw.print(ent.getKey());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009527 if (dumpAll) {
9528 pw.println(":");
9529 ArrayList<Intent> intents = ent.getValue();
9530 final int N = intents.size();
9531 for (int i=0; i<N; i++) {
9532 sb.setLength(0);
9533 sb.append(" Intent: ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009534 intents.get(i).toShortString(sb, false, true, false, false);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009535 pw.println(sb.toString());
9536 Bundle bundle = intents.get(i).getExtras();
9537 if (bundle != null) {
9538 pw.print(" ");
9539 pw.println(bundle.toString());
9540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009541 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009542 } else {
9543 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009544 }
9545 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009546 needSep = true;
9547 }
9548
9549 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009550 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009551 for (BroadcastQueue queue : mBroadcastQueues) {
9552 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9553 + queue.mBroadcastsScheduled);
9554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009555 pw.println(" mHandler:");
9556 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009557 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009558 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009559
9560 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009561 }
9562
Marco Nelissen18cb2872011-11-15 11:19:53 -08009563 /**
9564 * Prints a list of ServiceRecords (dumpsys activity services)
9565 */
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009566 boolean dumpServicesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009567 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009568 boolean needSep = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009569
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009570 ItemMatcher matcher = new ItemMatcher();
9571 matcher.build(args, opti);
9572
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009573 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009574 try {
9575 List<UserInfo> users = AppGlobals.getPackageManager().getUsers();
9576 for (UserInfo user : users) {
9577 if (mServiceMap.getAllServices(user.id).size() > 0) {
9578 boolean printed = false;
9579 long nowReal = SystemClock.elapsedRealtime();
9580 Iterator<ServiceRecord> it = mServiceMap.getAllServices(
9581 user.id).iterator();
9582 needSep = false;
9583 while (it.hasNext()) {
9584 ServiceRecord r = it.next();
9585 if (!matcher.match(r, r.name)) {
9586 continue;
9587 }
9588 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9589 continue;
9590 }
9591 if (!printed) {
9592 pw.println(" Active services:");
9593 printed = true;
9594 }
9595 if (needSep) {
9596 pw.println();
9597 }
9598 pw.print(" * ");
9599 pw.println(r);
9600 if (dumpAll) {
9601 r.dump(pw, " ");
9602 needSep = true;
9603 } else {
9604 pw.print(" app=");
9605 pw.println(r.app);
9606 pw.print(" created=");
9607 TimeUtils.formatDuration(r.createTime, nowReal, pw);
9608 pw.print(" started=");
9609 pw.print(r.startRequested);
9610 pw.print(" connections=");
9611 pw.println(r.connections.size());
9612 if (r.connections.size() > 0) {
9613 pw.println(" Connections:");
9614 for (ArrayList<ConnectionRecord> clist : r.connections.values()) {
9615 for (int i = 0; i < clist.size(); i++) {
9616 ConnectionRecord conn = clist.get(i);
9617 pw.print(" ");
9618 pw.print(conn.binding.intent.intent.getIntent()
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009619 .toShortString(false, false, false, false));
Amith Yamasani742a6712011-05-04 14:49:28 -07009620 pw.print(" -> ");
9621 ProcessRecord proc = conn.binding.client;
9622 pw.println(proc != null ? proc.toShortString() : "null");
9623 }
9624 }
Dianne Hackborn8ec8d412011-11-14 18:27:24 -08009625 }
9626 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009627 if (dumpClient && r.app != null && r.app.thread != null) {
9628 pw.println(" Client:");
9629 pw.flush();
9630 try {
9631 TransferPipe tp = new TransferPipe();
9632 try {
9633 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(),
9634 r, args);
9635 tp.setBufferPrefix(" ");
9636 // Short timeout, since blocking here can
9637 // deadlock with the application.
9638 tp.go(fd, 2000);
9639 } finally {
9640 tp.kill();
9641 }
9642 } catch (IOException e) {
9643 pw.println(" Failure while dumping the service: " + e);
9644 } catch (RemoteException e) {
9645 pw.println(" Got a RemoteException while dumping the service");
9646 }
9647 needSep = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009648 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009649 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009650 needSep = printed;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009652 }
Amith Yamasani742a6712011-05-04 14:49:28 -07009653 } catch (RemoteException re) {
9654
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009656
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009657 if (mPendingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009658 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009659 for (int i=0; i<mPendingServices.size(); i++) {
9660 ServiceRecord r = mPendingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009661 if (!matcher.match(r, r.name)) {
9662 continue;
9663 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009664 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9665 continue;
9666 }
9667 if (!printed) {
9668 if (needSep) pw.println(" ");
9669 needSep = true;
9670 pw.println(" Pending services:");
9671 printed = true;
9672 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009673 pw.print(" * Pending "); pw.println(r);
9674 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009675 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009676 needSep = true;
9677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009678
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009679 if (mRestartingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009680 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009681 for (int i=0; i<mRestartingServices.size(); i++) {
9682 ServiceRecord r = mRestartingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009683 if (!matcher.match(r, r.name)) {
9684 continue;
9685 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009686 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9687 continue;
9688 }
9689 if (!printed) {
9690 if (needSep) pw.println(" ");
9691 needSep = true;
9692 pw.println(" Restarting services:");
9693 printed = true;
9694 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009695 pw.print(" * Restarting "); pw.println(r);
9696 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009697 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009698 needSep = true;
9699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009700
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009701 if (mStoppingServices.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009702 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009703 for (int i=0; i<mStoppingServices.size(); i++) {
9704 ServiceRecord r = mStoppingServices.get(i);
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009705 if (!matcher.match(r, r.name)) {
9706 continue;
9707 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009708 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
9709 continue;
9710 }
9711 if (!printed) {
9712 if (needSep) pw.println(" ");
9713 needSep = true;
9714 pw.println(" Stopping services:");
9715 printed = true;
9716 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009717 pw.print(" * Stopping "); pw.println(r);
9718 r.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009719 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009720 needSep = true;
9721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009722
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009723 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009724 if (mServiceConnections.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009725 boolean printed = false;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009726 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009727 = mServiceConnections.values().iterator();
9728 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009729 ArrayList<ConnectionRecord> r = it.next();
9730 for (int i=0; i<r.size(); i++) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009731 ConnectionRecord cr = r.get(i);
9732 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
9733 continue;
9734 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009735 if (dumpPackage != null && (cr.binding.client == null
9736 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
9737 continue;
9738 }
9739 if (!printed) {
9740 if (needSep) pw.println(" ");
9741 needSep = true;
9742 pw.println(" Connection bindings to services:");
9743 printed = true;
9744 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009745 pw.print(" * "); pw.println(cr);
9746 cr.dump(pw, " ");
Dianne Hackborn43d9ac82010-08-25 15:06:25 -07009747 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009748 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009749 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009750 }
9751 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009752
9753 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009754 }
9755
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009756 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009757 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009758 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009759
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009760 ItemMatcher matcher = new ItemMatcher();
9761 matcher.build(args, opti);
9762
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009763 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009764
9765 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009766
9767 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009768 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009769 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009770 ContentProviderRecord r = mLaunchingProviders.get(i);
9771 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9772 continue;
9773 }
9774 if (!printed) {
9775 if (needSep) pw.println(" ");
9776 needSep = true;
9777 pw.println(" Launching content providers:");
9778 printed = true;
9779 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009780 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009781 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009782 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009783 }
9784
9785 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009786 if (needSep) pw.println();
9787 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009788 pw.println("Granted Uri Permissions:");
9789 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9790 int uid = mGrantedUriPermissions.keyAt(i);
9791 HashMap<Uri, UriPermission> perms
9792 = mGrantedUriPermissions.valueAt(i);
9793 pw.print(" * UID "); pw.print(uid);
9794 pw.println(" holds:");
9795 for (UriPermission perm : perms.values()) {
9796 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009797 if (dumpAll) {
9798 perm.dump(pw, " ");
9799 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009800 }
9801 }
9802 needSep = true;
9803 }
9804
9805 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009806 }
9807
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009808 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009809 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009810 boolean needSep = false;
9811
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009812 if (mIntentSenderRecords.size() > 0) {
9813 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009814 Iterator<WeakReference<PendingIntentRecord>> it
9815 = mIntentSenderRecords.values().iterator();
9816 while (it.hasNext()) {
9817 WeakReference<PendingIntentRecord> ref = it.next();
9818 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009819 if (dumpPackage != null && (rec == null
9820 || !dumpPackage.equals(rec.key.packageName))) {
9821 continue;
9822 }
9823 if (!printed) {
9824 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9825 printed = true;
9826 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009827 needSep = true;
9828 if (rec != null) {
9829 pw.print(" * "); pw.println(rec);
9830 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009831 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009833 } else {
9834 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009835 }
9836 }
9837 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009838
9839 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009840 }
9841
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009842 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009843 String prefix, String label, boolean complete, boolean brief, boolean client,
9844 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009845 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009846 boolean needNL = false;
9847 final String innerPrefix = prefix + " ";
9848 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009849 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009850 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009851 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9852 continue;
9853 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009854 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009855 if (needNL) {
9856 pw.println(" ");
9857 needNL = false;
9858 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009859 if (lastTask != r.task) {
9860 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009861 pw.print(prefix);
9862 pw.print(full ? "* " : " ");
9863 pw.println(lastTask);
9864 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009865 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009866 } else if (complete) {
9867 // Complete + brief == give a summary. Isn't that obvious?!?
9868 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009869 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009870 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009871 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009872 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009873 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009874 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9875 pw.print(" #"); pw.print(i); pw.print(": ");
9876 pw.println(r);
9877 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009878 r.dump(pw, innerPrefix);
9879 } else if (complete) {
9880 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009881 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009882 if (r.app != null) {
9883 pw.print(innerPrefix); pw.println(r.app);
9884 }
9885 }
9886 if (client && r.app != null && r.app.thread != null) {
9887 // flush anything that is already in the PrintWriter since the thread is going
9888 // to write to the file descriptor directly
9889 pw.flush();
9890 try {
9891 TransferPipe tp = new TransferPipe();
9892 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009893 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9894 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009895 // Short timeout, since blocking here can
9896 // deadlock with the application.
9897 tp.go(fd, 2000);
9898 } finally {
9899 tp.kill();
9900 }
9901 } catch (IOException e) {
9902 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9903 } catch (RemoteException e) {
9904 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9905 }
9906 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009908 }
9909 }
9910
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009911 private static String buildOomTag(String prefix, String space, int val, int base) {
9912 if (val == base) {
9913 if (space == null) return prefix;
9914 return prefix + " ";
9915 }
9916 return prefix + "+" + Integer.toString(val-base);
9917 }
9918
9919 private static final int dumpProcessList(PrintWriter pw,
9920 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009921 String prefix, String normalLabel, String persistentLabel,
9922 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009923 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009924 final int N = list.size()-1;
9925 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009926 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009927 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9928 continue;
9929 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009930 pw.println(String.format("%s%s #%2d: %s",
9931 prefix, (r.persistent ? persistentLabel : normalLabel),
9932 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009933 if (r.persistent) {
9934 numPers++;
9935 }
9936 }
9937 return numPers;
9938 }
9939
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009940 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009941 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009942 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009943 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009944
Dianne Hackborn905577f2011-09-07 18:31:28 -07009945 ArrayList<Pair<ProcessRecord, Integer>> list
9946 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9947 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009948 ProcessRecord r = origList.get(i);
9949 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9950 continue;
9951 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009952 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9953 }
9954
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009955 if (list.size() <= 0) {
9956 return false;
9957 }
9958
Dianne Hackborn905577f2011-09-07 18:31:28 -07009959 Comparator<Pair<ProcessRecord, Integer>> comparator
9960 = new Comparator<Pair<ProcessRecord, Integer>>() {
9961 @Override
9962 public int compare(Pair<ProcessRecord, Integer> object1,
9963 Pair<ProcessRecord, Integer> object2) {
9964 if (object1.first.setAdj != object2.first.setAdj) {
9965 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9966 }
9967 if (object1.second.intValue() != object2.second.intValue()) {
9968 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9969 }
9970 return 0;
9971 }
9972 };
9973
9974 Collections.sort(list, comparator);
9975
Dianne Hackborn287952c2010-09-22 22:34:31 -07009976 final long curRealtime = SystemClock.elapsedRealtime();
9977 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9978 final long curUptime = SystemClock.uptimeMillis();
9979 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9980
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009981 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009982 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009983 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009984 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009985 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009986 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9987 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009988 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9989 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009990 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9991 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009992 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9993 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009994 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009995 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009996 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9997 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9998 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9999 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
10000 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
10001 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
10002 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
10003 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070010004 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
10005 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -070010006 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
10007 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010008 } else {
10009 oomAdj = Integer.toString(r.setAdj);
10010 }
10011 String schedGroup;
10012 switch (r.setSchedGroup) {
10013 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
10014 schedGroup = "B";
10015 break;
10016 case Process.THREAD_GROUP_DEFAULT:
10017 schedGroup = "F";
10018 break;
10019 default:
10020 schedGroup = Integer.toString(r.setSchedGroup);
10021 break;
10022 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010023 String foreground;
10024 if (r.foregroundActivities) {
10025 foreground = "A";
10026 } else if (r.foregroundServices) {
10027 foreground = "S";
10028 } else {
10029 foreground = " ";
10030 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070010031 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -070010032 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010033 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
10034 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -070010035 if (r.adjSource != null || r.adjTarget != null) {
10036 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010037 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070010038 if (r.adjTarget instanceof ComponentName) {
10039 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
10040 } else if (r.adjTarget != null) {
10041 pw.print(r.adjTarget.toString());
10042 } else {
10043 pw.print("{null}");
10044 }
10045 pw.print("<=");
10046 if (r.adjSource instanceof ProcessRecord) {
10047 pw.print("Proc{");
10048 pw.print(((ProcessRecord)r.adjSource).toShortString());
10049 pw.println("}");
10050 } else if (r.adjSource != null) {
10051 pw.println(r.adjSource.toString());
10052 } else {
10053 pw.println("{null}");
10054 }
10055 }
10056 if (inclDetails) {
10057 pw.print(prefix);
10058 pw.print(" ");
10059 pw.print("oom: max="); pw.print(r.maxAdj);
10060 pw.print(" hidden="); pw.print(r.hiddenAdj);
10061 pw.print(" curRaw="); pw.print(r.curRawAdj);
10062 pw.print(" setRaw="); pw.print(r.setRawAdj);
10063 pw.print(" cur="); pw.print(r.curAdj);
10064 pw.print(" set="); pw.println(r.setAdj);
10065 pw.print(prefix);
10066 pw.print(" ");
10067 pw.print("keeping="); pw.print(r.keeping);
10068 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010069 pw.print(" empty="); pw.print(r.empty);
10070 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -070010071
10072 if (!r.keeping) {
10073 if (r.lastWakeTime != 0) {
10074 long wtime;
10075 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
10076 synchronized (stats) {
10077 wtime = stats.getProcessWakeTime(r.info.uid,
10078 r.pid, curRealtime);
10079 }
10080 long timeUsed = wtime - r.lastWakeTime;
10081 pw.print(prefix);
10082 pw.print(" ");
10083 pw.print("keep awake over ");
10084 TimeUtils.formatDuration(realtimeSince, pw);
10085 pw.print(" used ");
10086 TimeUtils.formatDuration(timeUsed, pw);
10087 pw.print(" (");
10088 pw.print((timeUsed*100)/realtimeSince);
10089 pw.println("%)");
10090 }
10091 if (r.lastCpuTime != 0) {
10092 long timeUsed = r.curCpuTime - r.lastCpuTime;
10093 pw.print(prefix);
10094 pw.print(" ");
10095 pw.print("run cpu over ");
10096 TimeUtils.formatDuration(uptimeSince, pw);
10097 pw.print(" used ");
10098 TimeUtils.formatDuration(timeUsed, pw);
10099 pw.print(" (");
10100 pw.print((timeUsed*100)/uptimeSince);
10101 pw.println("%)");
10102 }
10103 }
10104 }
10105 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010106 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010107 }
10108
Dianne Hackbornb437e092011-08-05 17:50:29 -070010109 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010110 ArrayList<ProcessRecord> procs;
10111 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010112 if (args != null && args.length > start
10113 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010114 procs = new ArrayList<ProcessRecord>();
10115 int pid = -1;
10116 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010117 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010118 } catch (NumberFormatException e) {
10119
10120 }
10121 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10122 ProcessRecord proc = mLruProcesses.get(i);
10123 if (proc.pid == pid) {
10124 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010125 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010126 procs.add(proc);
10127 }
10128 }
10129 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010130 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010131 return null;
10132 }
10133 } else {
10134 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10135 }
10136 }
10137 return procs;
10138 }
10139
10140 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10141 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010142 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010143 if (procs == null) {
10144 return;
10145 }
10146
10147 long uptime = SystemClock.uptimeMillis();
10148 long realtime = SystemClock.elapsedRealtime();
10149 pw.println("Applications Graphics Acceleration Info:");
10150 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10151
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010152 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10153 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010154 if (r.thread != null) {
10155 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10156 pw.flush();
10157 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010158 TransferPipe tp = new TransferPipe();
10159 try {
10160 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10161 tp.go(fd);
10162 } finally {
10163 tp.kill();
10164 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010165 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010166 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010167 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010168 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010169 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010170 pw.flush();
10171 }
10172 }
10173 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010174 }
10175
Jeff Brown6754ba22011-12-14 20:20:01 -080010176 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10177 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10178 if (procs == null) {
10179 return;
10180 }
10181
10182 pw.println("Applications Database Info:");
10183
10184 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10185 ProcessRecord r = procs.get(i);
10186 if (r.thread != null) {
10187 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10188 pw.flush();
10189 try {
10190 TransferPipe tp = new TransferPipe();
10191 try {
10192 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10193 tp.go(fd);
10194 } finally {
10195 tp.kill();
10196 }
10197 } catch (IOException e) {
10198 pw.println("Failure while dumping the app: " + r);
10199 pw.flush();
10200 } catch (RemoteException e) {
10201 pw.println("Got a RemoteException while dumping the app " + r);
10202 pw.flush();
10203 }
10204 }
10205 }
10206 }
10207
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010208 final static class MemItem {
10209 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010210 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010211 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010212 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010213 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010214
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010215 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010216 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010217 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010218 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010219 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010220 }
10221 }
10222
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010223 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010224 boolean sort) {
10225 if (sort) {
10226 Collections.sort(items, new Comparator<MemItem>() {
10227 @Override
10228 public int compare(MemItem lhs, MemItem rhs) {
10229 if (lhs.pss < rhs.pss) {
10230 return 1;
10231 } else if (lhs.pss > rhs.pss) {
10232 return -1;
10233 }
10234 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010235 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010236 });
10237 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010238
10239 for (int i=0; i<items.size(); i++) {
10240 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010241 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010242 if (mi.subitems != null) {
10243 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10244 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010245 }
10246 }
10247
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010248 // These are in KB.
10249 static final long[] DUMP_MEM_BUCKETS = new long[] {
10250 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10251 120*1024, 160*1024, 200*1024,
10252 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10253 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10254 };
10255
Dianne Hackborn672342c2011-11-29 11:29:02 -080010256 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10257 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010258 int start = label.lastIndexOf('.');
10259 if (start >= 0) start++;
10260 else start = 0;
10261 int end = label.length();
10262 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10263 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10264 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10265 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010266 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010267 out.append(label, start, end);
10268 return;
10269 }
10270 }
10271 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010272 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010273 out.append(label, start, end);
10274 }
10275
10276 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10277 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10278 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10279 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10280 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10281 };
10282 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10283 "System", "Persistent", "Foreground",
10284 "Visible", "Perceptible", "Heavy Weight",
10285 "Backup", "A Services", "Home", "Previous",
10286 "B Services", "Background"
10287 };
10288
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010289 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010290 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010291 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010292 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010293 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010294
10295 int opti = 0;
10296 while (opti < args.length) {
10297 String opt = args[opti];
10298 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10299 break;
10300 }
10301 opti++;
10302 if ("-a".equals(opt)) {
10303 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010304 } else if ("--oom".equals(opt)) {
10305 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010306 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010307 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010308 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010309 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010310 pw.println("If [process] is specified it can be the name or ");
10311 pw.println("pid of a specific process to dump.");
10312 return;
10313 } else {
10314 pw.println("Unknown argument: " + opt + "; use -h for help");
10315 }
10316 }
10317
10318 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010319 if (procs == null) {
10320 return;
10321 }
10322
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010323 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010324 long uptime = SystemClock.uptimeMillis();
10325 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010326
10327 if (procs.size() == 1 || isCheckinRequest) {
10328 dumpAll = true;
10329 }
10330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010331 if (isCheckinRequest) {
10332 // short checkin version
10333 pw.println(uptime + "," + realtime);
10334 pw.flush();
10335 } else {
10336 pw.println("Applications Memory Usage (kB):");
10337 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10338 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010339
Dianne Hackbornb437e092011-08-05 17:50:29 -070010340 String[] innerArgs = new String[args.length-opti];
10341 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10342
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010343 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10344 long nativePss=0, dalvikPss=0, otherPss=0;
10345 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10346
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010347 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10348 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10349 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010350
10351 long totalPss = 0;
10352
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010353 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10354 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010355 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010356 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010357 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10358 pw.flush();
10359 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010360 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010361 if (dumpAll) {
10362 try {
10363 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10364 } catch (RemoteException e) {
10365 if (!isCheckinRequest) {
10366 pw.println("Got RemoteException!");
10367 pw.flush();
10368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010369 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010370 } else {
10371 mi = new Debug.MemoryInfo();
10372 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010373 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010374
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010375 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010376 long myTotalPss = mi.getTotalPss();
10377 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010378 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010379 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010380 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010381
10382 nativePss += mi.nativePss;
10383 dalvikPss += mi.dalvikPss;
10384 otherPss += mi.otherPss;
10385 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10386 long mem = mi.getOtherPss(j);
10387 miscPss[j] += mem;
10388 otherPss -= mem;
10389 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010390
10391 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010392 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10393 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010394 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010395 if (oomProcs[oomIndex] == null) {
10396 oomProcs[oomIndex] = new ArrayList<MemItem>();
10397 }
10398 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010399 break;
10400 }
10401 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010403 }
10404 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010405
10406 if (!isCheckinRequest && procs.size() > 1) {
10407 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10408
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010409 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10410 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10411 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010412 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010413 String label = Debug.MemoryInfo.getOtherLabel(j);
10414 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010415 }
10416
Dianne Hackbornb437e092011-08-05 17:50:29 -070010417 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10418 for (int j=0; j<oomPss.length; j++) {
10419 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010420 String label = DUMP_MEM_OOM_LABEL[j];
10421 MemItem item = new MemItem(label, label, oomPss[j],
10422 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010423 item.subitems = oomProcs[j];
10424 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010425 }
10426 }
10427
Dianne Hackborn672342c2011-11-29 11:29:02 -080010428 if (outTag != null || outStack != null) {
10429 if (outTag != null) {
10430 appendMemBucket(outTag, totalPss, "total", false);
10431 }
10432 if (outStack != null) {
10433 appendMemBucket(outStack, totalPss, "total", true);
10434 }
10435 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010436 for (int i=0; i<oomMems.size(); i++) {
10437 MemItem miCat = oomMems.get(i);
10438 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10439 continue;
10440 }
10441 if (miCat.id < ProcessList.SERVICE_ADJ
10442 || miCat.id == ProcessList.HOME_APP_ADJ
10443 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010444 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10445 outTag.append(" / ");
10446 }
10447 if (outStack != null) {
10448 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10449 if (firstLine) {
10450 outStack.append(":");
10451 firstLine = false;
10452 }
10453 outStack.append("\n\t at ");
10454 } else {
10455 outStack.append("$");
10456 }
10457 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010458 for (int j=0; j<miCat.subitems.size(); j++) {
10459 MemItem mi = miCat.subitems.get(j);
10460 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010461 if (outTag != null) {
10462 outTag.append(" ");
10463 }
10464 if (outStack != null) {
10465 outStack.append("$");
10466 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010467 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010468 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10469 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10470 }
10471 if (outStack != null) {
10472 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10473 }
10474 }
10475 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10476 outStack.append("(");
10477 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10478 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10479 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10480 outStack.append(":");
10481 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10482 }
10483 }
10484 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010485 }
10486 }
10487 }
10488 }
10489
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010490 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010491 pw.println();
10492 pw.println("Total PSS by process:");
10493 dumpMemItems(pw, " ", procMems, true);
10494 pw.println();
10495 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010496 pw.println("Total PSS by OOM adjustment:");
10497 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010498 if (!oomOnly) {
10499 PrintWriter out = categoryPw != null ? categoryPw : pw;
10500 out.println();
10501 out.println("Total PSS by category:");
10502 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010503 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010504 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010505 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010506 final int[] SINGLE_LONG_FORMAT = new int[] {
10507 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10508 };
10509 long[] longOut = new long[1];
10510 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10511 SINGLE_LONG_FORMAT, null, longOut, null);
10512 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10513 longOut[0] = 0;
10514 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10515 SINGLE_LONG_FORMAT, null, longOut, null);
10516 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10517 longOut[0] = 0;
10518 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10519 SINGLE_LONG_FORMAT, null, longOut, null);
10520 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10521 longOut[0] = 0;
10522 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10523 SINGLE_LONG_FORMAT, null, longOut, null);
10524 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10525 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10526 pw.print(shared); pw.println(" kB");
10527 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10528 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010530 }
10531
10532 /**
10533 * Searches array of arguments for the specified string
10534 * @param args array of argument strings
10535 * @param value value to search for
10536 * @return true if the value is contained in the array
10537 */
10538 private static boolean scanArgs(String[] args, String value) {
10539 if (args != null) {
10540 for (String arg : args) {
10541 if (value.equals(arg)) {
10542 return true;
10543 }
10544 }
10545 }
10546 return false;
10547 }
10548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010549 private final void killServicesLocked(ProcessRecord app,
10550 boolean allowRestart) {
10551 // Report disconnected services.
10552 if (false) {
10553 // XXX we are letting the client link to the service for
10554 // death notifications.
10555 if (app.services.size() > 0) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010556 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010557 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010558 ServiceRecord r = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010559 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010560 Iterator<ArrayList<ConnectionRecord>> jt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010561 = r.connections.values().iterator();
10562 while (jt.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010563 ArrayList<ConnectionRecord> cl = jt.next();
10564 for (int i=0; i<cl.size(); i++) {
10565 ConnectionRecord c = cl.get(i);
10566 if (c.binding.client != app) {
10567 try {
10568 //c.conn.connected(r.className, null);
10569 } catch (Exception e) {
10570 // todo: this should be asynchronous!
10571 Slog.w(TAG, "Exception thrown disconnected servce "
10572 + r.shortName
10573 + " from app " + app.processName, e);
10574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010575 }
10576 }
10577 }
10578 }
10579 }
10580 }
10581 }
10582
10583 // Clean up any connections this application has to other services.
10584 if (app.connections.size() > 0) {
10585 Iterator<ConnectionRecord> it = app.connections.iterator();
10586 while (it.hasNext()) {
10587 ConnectionRecord r = it.next();
10588 removeConnectionLocked(r, app, null);
10589 }
10590 }
10591 app.connections.clear();
10592
10593 if (app.services.size() != 0) {
10594 // Any services running in the application need to be placed
10595 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -070010596 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010597 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010598 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010599 synchronized (sr.stats.getBatteryStats()) {
10600 sr.stats.stopLaunchedLocked();
10601 }
10602 sr.app = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010603 sr.isolatedProc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010604 sr.executeNesting = 0;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010605 if (mStoppingServices.remove(sr)) {
10606 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
10607 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010608
10609 boolean hasClients = sr.bindings.size() > 0;
10610 if (hasClients) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010611 Iterator<IntentBindRecord> bindings
10612 = sr.bindings.values().iterator();
10613 while (bindings.hasNext()) {
10614 IntentBindRecord b = bindings.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080010615 if (DEBUG_SERVICE) Slog.v(TAG, "Killing binding " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010616 + ": shouldUnbind=" + b.hasBound);
10617 b.binder = null;
10618 b.requested = b.received = b.hasBound = false;
10619 }
10620 }
10621
Dianne Hackborn070783f2010-12-29 16:46:28 -080010622 if (sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
10623 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010624 Slog.w(TAG, "Service crashed " + sr.crashCount
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010625 + " times, stopping: " + sr);
Doug Zongker2bec3d42009-12-04 12:52:44 -080010626 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010627 sr.crashCount, sr.shortName, app.pid);
10628 bringDownServiceLocked(sr, true);
10629 } else if (!allowRestart) {
10630 bringDownServiceLocked(sr, true);
10631 } else {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010632 boolean canceled = scheduleServiceRestartLocked(sr, true);
10633
10634 // Should the service remain running? Note that in the
10635 // extreme case of so many attempts to deliver a command
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010636 // that it failed we also will stop it here.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010637 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
10638 if (sr.pendingStarts.size() == 0) {
10639 sr.startRequested = false;
10640 if (!hasClients) {
10641 // Whoops, no reason to restart!
10642 bringDownServiceLocked(sr, true);
10643 }
10644 }
10645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010646 }
10647 }
10648
10649 if (!allowRestart) {
10650 app.services.clear();
10651 }
10652 }
10653
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010654 // Make sure we have no more records on the stopping list.
10655 int i = mStoppingServices.size();
10656 while (i > 0) {
10657 i--;
10658 ServiceRecord sr = mStoppingServices.get(i);
10659 if (sr.app == app) {
10660 mStoppingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010661 if (DEBUG_SERVICE) Slog.v(TAG, "killServices remove stopping " + sr);
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010662 }
10663 }
10664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010665 app.executingServices.clear();
10666 }
10667
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010668 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10669 ContentProviderRecord cpr, boolean always) {
10670 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10671
10672 if (!inLaunching || always) {
10673 synchronized (cpr) {
10674 cpr.launchingApp = null;
10675 cpr.notifyAll();
10676 }
10677 mProviderMap.removeProviderByClass(cpr.name, UserId.getUserId(cpr.uid));
10678 String names[] = cpr.info.authority.split(";");
10679 for (int j = 0; j < names.length; j++) {
10680 mProviderMap.removeProviderByName(names[j], UserId.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010681 }
10682 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010683
10684 for (int i=0; i<cpr.connections.size(); i++) {
10685 ContentProviderConnection conn = cpr.connections.get(i);
10686 if (conn.waiting) {
10687 // If this connection is waiting for the provider, then we don't
10688 // need to mess with its process unless we are always removing
10689 // or for some reason the provider is not currently launching.
10690 if (inLaunching && !always) {
10691 continue;
10692 }
10693 }
10694 ProcessRecord capp = conn.client;
10695 conn.dead = true;
10696 if (conn.stableCount > 0) {
10697 if (!capp.persistent && capp.thread != null
10698 && capp.pid != 0
10699 && capp.pid != MY_PID) {
10700 Slog.i(TAG, "Kill " + capp.processName
10701 + " (pid " + capp.pid + "): provider " + cpr.info.name
10702 + " in dying process " + (proc != null ? proc.processName : "??"));
10703 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10704 capp.processName, capp.setAdj, "dying provider "
10705 + cpr.name.toShortString());
10706 Process.killProcessQuiet(capp.pid);
10707 }
10708 } else if (capp.thread != null && conn.provider.provider != null) {
10709 try {
10710 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10711 } catch (RemoteException e) {
10712 }
10713 // In the protocol here, we don't expect the client to correctly
10714 // clean up this connection, we'll just remove it.
10715 cpr.connections.remove(i);
10716 conn.client.conProviders.remove(conn);
10717 }
10718 }
10719
10720 if (inLaunching && always) {
10721 mLaunchingProviders.remove(cpr);
10722 }
10723 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010724 }
10725
10726 /**
10727 * Main code for cleaning up a process when it has gone away. This is
10728 * called both as a result of the process dying, or directly when stopping
10729 * a process when running in single process mode.
10730 */
10731 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010732 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010733 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010734 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010735 }
10736
Dianne Hackborn36124872009-10-08 16:22:03 -070010737 mProcessesToGc.remove(app);
10738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010739 // Dismiss any open dialogs.
10740 if (app.crashDialog != null) {
10741 app.crashDialog.dismiss();
10742 app.crashDialog = null;
10743 }
10744 if (app.anrDialog != null) {
10745 app.anrDialog.dismiss();
10746 app.anrDialog = null;
10747 }
10748 if (app.waitDialog != null) {
10749 app.waitDialog.dismiss();
10750 app.waitDialog = null;
10751 }
10752
10753 app.crashing = false;
10754 app.notResponding = false;
10755
10756 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010757 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010758 app.thread = null;
10759 app.forcingToForeground = null;
10760 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010761 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010762 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010763 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010764
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010765 killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010766
10767 boolean restart = false;
10768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010769 // Remove published content providers.
10770 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010771 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010772 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010773 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010774
10775 final boolean always = app.bad || !allowRestart;
10776 if (removeDyingProviderLocked(app, cpr, always) || always) {
10777 // We left the provider in the launching list, need to
10778 // restart it.
10779 restart = true;
10780 }
10781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010782 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010783 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010784 }
10785 app.pubProviders.clear();
10786 }
10787
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010788 // Take care of any launching providers waiting for this process.
10789 if (checkAppInLaunchingProvidersLocked(app, false)) {
10790 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010791 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010793 // Unregister from connected content providers.
10794 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010795 for (int i=0; i<app.conProviders.size(); i++) {
10796 ContentProviderConnection conn = app.conProviders.get(i);
10797 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010798 }
10799 app.conProviders.clear();
10800 }
10801
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010802 // At this point there may be remaining entries in mLaunchingProviders
10803 // where we were the only one waiting, so they are no longer of use.
10804 // Look for these and clean up if found.
10805 // XXX Commented out for now. Trying to figure out a way to reproduce
10806 // the actual situation to identify what is actually going on.
10807 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010808 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010809 ContentProviderRecord cpr = (ContentProviderRecord)
10810 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010811 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010812 synchronized (cpr) {
10813 cpr.launchingApp = null;
10814 cpr.notifyAll();
10815 }
10816 }
10817 }
10818 }
10819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010820 skipCurrentReceiverLocked(app);
10821
10822 // Unregister any receivers.
10823 if (app.receivers.size() > 0) {
10824 Iterator<ReceiverList> it = app.receivers.iterator();
10825 while (it.hasNext()) {
10826 removeReceiverLocked(it.next());
10827 }
10828 app.receivers.clear();
10829 }
10830
Christopher Tate181fafa2009-05-14 11:12:14 -070010831 // If the app is undergoing backup, tell the backup manager about it
10832 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010833 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010834 try {
10835 IBackupManager bm = IBackupManager.Stub.asInterface(
10836 ServiceManager.getService(Context.BACKUP_SERVICE));
10837 bm.agentDisconnected(app.info.packageName);
10838 } catch (RemoteException e) {
10839 // can't happen; backup manager is local
10840 }
10841 }
10842
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010843 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10844 ProcessChangeItem item = mPendingProcessChanges.get(i);
10845 if (item.pid == app.pid) {
10846 mPendingProcessChanges.remove(i);
10847 mAvailProcessChanges.add(item);
10848 }
10849 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010850 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010852 // If the caller is restarting this app, then leave it in its
10853 // current lists and let the caller take care of it.
10854 if (restarting) {
10855 return;
10856 }
10857
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010858 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010859 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010860 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010861 mProcessNames.remove(app.processName, app.uid);
10862 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010863 if (mHeavyWeightProcess == app) {
10864 mHeavyWeightProcess = null;
10865 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010867 } else if (!app.removed) {
10868 // This app is persistent, so we need to keep its record around.
10869 // If it is not already on the pending app list, add it there
10870 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010871 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10872 mPersistentStartingProcesses.add(app);
10873 restart = true;
10874 }
10875 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010876 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10877 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010878 mProcessesOnHold.remove(app);
10879
The Android Open Source Project4df24232009-03-05 14:34:35 -080010880 if (app == mHomeProcess) {
10881 mHomeProcess = null;
10882 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010883 if (app == mPreviousProcess) {
10884 mPreviousProcess = null;
10885 }
10886
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010887 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010888 // We have components that still need to be running in the
10889 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010890 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010891 startProcessLocked(app, "restart", app.processName);
10892 } else if (app.pid > 0 && app.pid != MY_PID) {
10893 // Goodbye!
10894 synchronized (mPidsSelfLocked) {
10895 mPidsSelfLocked.remove(app.pid);
10896 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10897 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010898 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010899 }
10900 }
10901
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010902 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10903 // Look through the content providers we are waiting to have launched,
10904 // and if any run in this process then either schedule a restart of
10905 // the process or kill the client waiting for it if this process has
10906 // gone bad.
10907 int NL = mLaunchingProviders.size();
10908 boolean restart = false;
10909 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010910 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010911 if (cpr.launchingApp == app) {
10912 if (!alwaysBad && !app.bad) {
10913 restart = true;
10914 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010915 removeDyingProviderLocked(app, cpr, true);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010916 NL = mLaunchingProviders.size();
10917 }
10918 }
10919 }
10920 return restart;
10921 }
10922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010923 // =========================================================
10924 // SERVICES
10925 // =========================================================
10926
10927 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
10928 ActivityManager.RunningServiceInfo info =
10929 new ActivityManager.RunningServiceInfo();
10930 info.service = r.name;
10931 if (r.app != null) {
10932 info.pid = r.app.pid;
10933 }
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010934 info.uid = r.appInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010935 info.process = r.processName;
10936 info.foreground = r.isForeground;
10937 info.activeSince = r.createTime;
10938 info.started = r.startRequested;
10939 info.clientCount = r.connections.size();
10940 info.crashCount = r.crashCount;
10941 info.lastActivityTime = r.lastActivity;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010942 if (r.isForeground) {
10943 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
10944 }
10945 if (r.startRequested) {
10946 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
10947 }
Dan Egnor42471dd2010-01-07 17:25:22 -080010948 if (r.app != null && r.app.pid == MY_PID) {
Dianne Hackborn3025ef32009-08-31 21:31:47 -070010949 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
10950 }
10951 if (r.app != null && r.app.persistent) {
10952 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
10953 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070010954
10955 for (ArrayList<ConnectionRecord> connl : r.connections.values()) {
10956 for (int i=0; i<connl.size(); i++) {
10957 ConnectionRecord conn = connl.get(i);
10958 if (conn.clientLabel != 0) {
10959 info.clientPackage = conn.binding.client.info.packageName;
10960 info.clientLabel = conn.clientLabel;
10961 return info;
10962 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010963 }
10964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010965 return info;
10966 }
10967
10968 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10969 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010970 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010971 synchronized (this) {
10972 ArrayList<ActivityManager.RunningServiceInfo> res
10973 = new ArrayList<ActivityManager.RunningServiceInfo>();
10974
Amith Yamasani742a6712011-05-04 14:49:28 -070010975 int userId = UserId.getUserId(Binder.getCallingUid());
10976 if (mServiceMap.getAllServices(userId).size() > 0) {
10977 Iterator<ServiceRecord> it
10978 = mServiceMap.getAllServices(userId).iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010979 while (it.hasNext() && res.size() < maxNum) {
10980 res.add(makeRunningServiceInfoLocked(it.next()));
10981 }
10982 }
10983
10984 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
10985 ServiceRecord r = mRestartingServices.get(i);
10986 ActivityManager.RunningServiceInfo info =
10987 makeRunningServiceInfoLocked(r);
10988 info.restarting = r.nextRestartTime;
10989 res.add(info);
10990 }
10991
10992 return res;
10993 }
10994 }
10995
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010996 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010997 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010998 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010999 int userId = UserId.getUserId(Binder.getCallingUid());
11000 ServiceRecord r = mServiceMap.getServiceByName(name, userId);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011001 if (r != null) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011002 for (ArrayList<ConnectionRecord> conn : r.connections.values()) {
11003 for (int i=0; i<conn.size(); i++) {
11004 if (conn.get(i).clientIntent != null) {
11005 return conn.get(i).clientIntent;
11006 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011007 }
11008 }
11009 }
11010 }
11011 return null;
11012 }
11013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011014 private final ServiceRecord findServiceLocked(ComponentName name,
11015 IBinder token) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011016 ServiceRecord r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011017 return r == token ? r : null;
11018 }
11019
11020 private final class ServiceLookupResult {
11021 final ServiceRecord record;
11022 final String permission;
11023
11024 ServiceLookupResult(ServiceRecord _record, String _permission) {
11025 record = _record;
11026 permission = _permission;
11027 }
11028 };
11029
11030 private ServiceLookupResult findServiceLocked(Intent service,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011031 String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011032 ServiceRecord r = null;
11033 if (service.getComponent() != null) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011034 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011035 }
11036 if (r == null) {
11037 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani483f3b02012-03-13 16:08:00 -070011038 r = mServiceMap.getServiceByIntent(filter, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011039 }
11040
11041 if (r == null) {
11042 try {
11043 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011044 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011045 service, resolvedType, 0, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011046 ServiceInfo sInfo =
11047 rInfo != null ? rInfo.serviceInfo : null;
11048 if (sInfo == null) {
11049 return null;
11050 }
11051
11052 ComponentName name = new ComponentName(
11053 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani742a6712011-05-04 14:49:28 -070011054 r = mServiceMap.getServiceByName(name, Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011055 } catch (RemoteException ex) {
11056 // pm is in same process, this will never happen.
11057 }
11058 }
11059 if (r != null) {
11060 int callingPid = Binder.getCallingPid();
11061 int callingUid = Binder.getCallingUid();
11062 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011063 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011064 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011065 if (!r.exported) {
11066 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11067 + " from pid=" + callingPid
11068 + ", uid=" + callingUid
11069 + " that is not exported from uid " + r.appInfo.uid);
11070 return new ServiceLookupResult(null, "not exported from uid "
11071 + r.appInfo.uid);
11072 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011073 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011074 + " from pid=" + callingPid
11075 + ", uid=" + callingUid
11076 + " requires " + r.permission);
11077 return new ServiceLookupResult(null, r.permission);
11078 }
11079 return new ServiceLookupResult(r, null);
11080 }
11081 return null;
11082 }
11083
11084 private class ServiceRestarter implements Runnable {
11085 private ServiceRecord mService;
11086
11087 void setService(ServiceRecord service) {
11088 mService = service;
11089 }
11090
11091 public void run() {
11092 synchronized(ActivityManagerService.this) {
11093 performServiceRestartLocked(mService);
11094 }
11095 }
11096 }
11097
11098 private ServiceLookupResult retrieveServiceLocked(Intent service,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011099 String resolvedType, int callingPid, int callingUid, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011100 ServiceRecord r = null;
Amith Yamasani742a6712011-05-04 14:49:28 -070011101 if (DEBUG_SERVICE)
11102 Slog.v(TAG, "retrieveServiceLocked: " + service + " type=" + resolvedType
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011103 + " callingUid=" + callingUid);
Amith Yamasani742a6712011-05-04 14:49:28 -070011104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011105 if (service.getComponent() != null) {
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011106 r = mServiceMap.getServiceByName(service.getComponent(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011107 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011108 if (r == null) {
11109 Intent.FilterComparison filter = new Intent.FilterComparison(service);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011110 r = mServiceMap.getServiceByIntent(filter, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070011111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011112 if (r == null) {
11113 try {
11114 ResolveInfo rInfo =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011115 AppGlobals.getPackageManager().resolveService(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011116 service, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011117 ServiceInfo sInfo =
11118 rInfo != null ? rInfo.serviceInfo : null;
11119 if (sInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011120 Slog.w(TAG, "Unable to start service " + service +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011121 ": not found");
11122 return null;
11123 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011124 if (userId > 0) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070011125 if (isSingleton(sInfo.processName, sInfo.applicationInfo)) {
11126 userId = 0;
11127 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011128 sInfo.applicationInfo = getAppInfoForUser(sInfo.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -070011129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011130 ComponentName name = new ComponentName(
11131 sInfo.applicationInfo.packageName, sInfo.name);
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011132 r = mServiceMap.getServiceByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011133 if (r == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011134 Intent.FilterComparison filter = new Intent.FilterComparison(
11135 service.cloneFilter());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011136 ServiceRestarter res = new ServiceRestarter();
11137 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
11138 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
11139 synchronized (stats) {
11140 ss = stats.getServiceStatsLocked(
11141 sInfo.applicationInfo.uid, sInfo.packageName,
11142 sInfo.name);
11143 }
Dianne Hackbornb1c4a2a2010-01-19 15:36:42 -080011144 r = new ServiceRecord(this, ss, name, filter, sInfo, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011145 res.setService(r);
Amith Yamasani742a6712011-05-04 14:49:28 -070011146 mServiceMap.putServiceByName(name, UserId.getUserId(r.appInfo.uid), r);
11147 mServiceMap.putServiceByIntent(filter, UserId.getUserId(r.appInfo.uid), r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011148
11149 // Make sure this component isn't in the pending list.
11150 int N = mPendingServices.size();
11151 for (int i=0; i<N; i++) {
11152 ServiceRecord pr = mPendingServices.get(i);
11153 if (pr.name.equals(name)) {
11154 mPendingServices.remove(i);
11155 i--;
11156 N--;
11157 }
11158 }
11159 }
11160 } catch (RemoteException ex) {
11161 // pm is in same process, this will never happen.
11162 }
11163 }
11164 if (r != null) {
11165 if (checkComponentPermission(r.permission,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011166 callingPid, callingUid, r.appInfo.uid, r.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011167 != PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011168 if (!r.exported) {
11169 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
11170 + " from pid=" + callingPid
11171 + ", uid=" + callingUid
11172 + " that is not exported from uid " + r.appInfo.uid);
11173 return new ServiceLookupResult(null, "not exported from uid "
11174 + r.appInfo.uid);
11175 }
Joe Onorato8a9b2202010-02-26 18:56:32 -080011176 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011177 + " from pid=" + callingPid
11178 + ", uid=" + callingUid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011179 + " requires " + r.permission);
11180 return new ServiceLookupResult(null, r.permission);
11181 }
11182 return new ServiceLookupResult(r, null);
11183 }
11184 return null;
11185 }
11186
Dianne Hackborn287952c2010-09-22 22:34:31 -070011187 private final void bumpServiceExecutingLocked(ServiceRecord r, String why) {
11188 if (DEBUG_SERVICE) Log.v(TAG, ">>> EXECUTING "
11189 + why + " of " + r + " in app " + r.app);
11190 else if (DEBUG_SERVICE_EXECUTING) Log.v(TAG, ">>> EXECUTING "
11191 + why + " of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011192 long now = SystemClock.uptimeMillis();
11193 if (r.executeNesting == 0 && r.app != null) {
11194 if (r.app.executingServices.size() == 0) {
11195 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
11196 msg.obj = r.app;
11197 mHandler.sendMessageAtTime(msg, now+SERVICE_TIMEOUT);
11198 }
11199 r.app.executingServices.add(r);
11200 }
11201 r.executeNesting++;
11202 r.executingStart = now;
11203 }
11204
11205 private final void sendServiceArgsLocked(ServiceRecord r,
11206 boolean oomAdjusted) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011207 final int N = r.pendingStarts.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011208 if (N == 0) {
11209 return;
11210 }
11211
Dianne Hackborn39792d22010-08-19 18:01:52 -070011212 while (r.pendingStarts.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011213 try {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011214 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011215 if (DEBUG_SERVICE) Slog.v(TAG, "Sending arguments to: "
11216 + r + " " + r.intent + " args=" + si.intent);
Dianne Hackborn3a28f222011-03-01 12:25:54 -080011217 if (si.intent == null && N > 1) {
11218 // If somehow we got a dummy null intent in the middle,
11219 // then skip it. DO NOT skip a null intent when it is
11220 // the only one in the list -- this is to support the
11221 // onStartCommand(null) case.
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011222 continue;
11223 }
Dianne Hackborn39792d22010-08-19 18:01:52 -070011224 si.deliveredTime = SystemClock.uptimeMillis();
11225 r.deliveredStarts.add(si);
11226 si.deliveryCount++;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011227 if (si.neededGrants != null) {
11228 grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
11229 si.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -070011230 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070011231 bumpServiceExecutingLocked(r, "start");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011232 if (!oomAdjusted) {
11233 oomAdjusted = true;
11234 updateOomAdjLocked(r.app);
11235 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011236 int flags = 0;
Dianne Hackbornd8f10242012-05-08 17:14:58 -070011237 if (si.deliveryCount > 1) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011238 flags |= Service.START_FLAG_RETRY;
11239 }
11240 if (si.doneExecutingCount > 0) {
11241 flags |= Service.START_FLAG_REDELIVERY;
11242 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011243 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011244 } catch (RemoteException e) {
11245 // Remote process gone... we'll let the normal cleanup take
11246 // care of this.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011247 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while scheduling start: " + r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011248 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011249 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011250 Slog.w(TAG, "Unexpected exception", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011251 break;
11252 }
11253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011254 }
11255
11256 private final boolean requestServiceBindingLocked(ServiceRecord r,
11257 IntentBindRecord i, boolean rebind) {
11258 if (r.app == null || r.app.thread == null) {
11259 // If service is not currently running, can't yet bind.
11260 return false;
11261 }
11262 if ((!i.requested || rebind) && i.apps.size() > 0) {
11263 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011264 bumpServiceExecutingLocked(r, "bind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011265 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind);
11266 if (!rebind) {
11267 i.requested = true;
11268 }
11269 i.hasBound = true;
11270 i.doRebind = false;
11271 } catch (RemoteException e) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011272 if (DEBUG_SERVICE) Slog.v(TAG, "Crashed while binding " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011273 return false;
11274 }
11275 }
11276 return true;
11277 }
11278
11279 private final void requestServiceBindingsLocked(ServiceRecord r) {
11280 Iterator<IntentBindRecord> bindings = r.bindings.values().iterator();
11281 while (bindings.hasNext()) {
11282 IntentBindRecord i = bindings.next();
11283 if (!requestServiceBindingLocked(r, i, false)) {
11284 break;
11285 }
11286 }
11287 }
11288
11289 private final void realStartServiceLocked(ServiceRecord r,
11290 ProcessRecord app) throws RemoteException {
11291 if (app.thread == null) {
11292 throw new RemoteException();
11293 }
Amith Yamasani742a6712011-05-04 14:49:28 -070011294 if (DEBUG_MU)
11295 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011296 + ", ProcessRecord.uid = " + app.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297 r.app = app;
The Android Open Source Project10592532009-03-18 17:39:46 -070011298 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011299
11300 app.services.add(r);
Dianne Hackborn287952c2010-09-22 22:34:31 -070011301 bumpServiceExecutingLocked(r, "create");
Dianne Hackborndd71fc82009-12-16 19:24:32 -080011302 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011303
11304 boolean created = false;
11305 try {
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011306 mStringBuilder.setLength(0);
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011307 r.intent.getIntent().toShortString(mStringBuilder, true, false, true, false);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011308 EventLog.writeEvent(EventLogTags.AM_CREATE_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011309 System.identityHashCode(r), r.shortName,
Dianne Hackborna33e3f72009-09-29 17:28:24 -070011310 mStringBuilder.toString(), r.app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011311 synchronized (r.stats.getBatteryStats()) {
11312 r.stats.startLaunchedLocked();
11313 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -070011314 ensurePackageDexOpt(r.serviceInfo.packageName);
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011315 app.thread.scheduleCreateService(r, r.serviceInfo,
11316 compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo));
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011317 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011318 created = true;
11319 } finally {
11320 if (!created) {
11321 app.services.remove(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011322 scheduleServiceRestartLocked(r, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011323 }
11324 }
11325
11326 requestServiceBindingsLocked(r);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011327
11328 // If the service is in the started state, and there are no
11329 // pending arguments, then fake up one so its onStartCommand() will
11330 // be called.
11331 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011332 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011333 null, null));
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011334 }
11335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011336 sendServiceArgsLocked(r, true);
11337 }
11338
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011339 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
11340 boolean allowCancel) {
11341 boolean canceled = false;
11342
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011343 final long now = SystemClock.uptimeMillis();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011344 long minDuration = SERVICE_RESTART_DURATION;
Dianne Hackborn6ccd2af2009-08-27 12:26:44 -070011345 long resetTime = SERVICE_RESET_RUN_DURATION;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011346
Dianne Hackborn070783f2010-12-29 16:46:28 -080011347 if ((r.serviceInfo.applicationInfo.flags
11348 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11349 minDuration /= 4;
11350 }
11351
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011352 // Any delivered but not yet finished starts should be put back
11353 // on the pending list.
11354 final int N = r.deliveredStarts.size();
11355 if (N > 0) {
11356 for (int i=N-1; i>=0; i--) {
11357 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
Dianne Hackborn39792d22010-08-19 18:01:52 -070011358 si.removeUriPermissionsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011359 if (si.intent == null) {
11360 // We'll generate this again if needed.
11361 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
11362 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
11363 r.pendingStarts.add(0, si);
11364 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
11365 dur *= 2;
11366 if (minDuration < dur) minDuration = dur;
11367 if (resetTime < dur) resetTime = dur;
11368 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011369 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011370 + r.name);
11371 canceled = true;
11372 }
11373 }
11374 r.deliveredStarts.clear();
11375 }
11376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011377 r.totalRestartCount++;
11378 if (r.restartDelay == 0) {
11379 r.restartCount++;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011380 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011381 } else {
11382 // If it has been a "reasonably long time" since the service
11383 // was started, then reset our restart duration back to
11384 // the beginning, so we don't infinitely increase the duration
11385 // on a service that just occasionally gets killed (which is
11386 // a normal case, due to process being killed to reclaim memory).
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011387 if (now > (r.restartTime+resetTime)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011388 r.restartCount = 1;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011389 r.restartDelay = minDuration;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011390 } else {
Dianne Hackborn070783f2010-12-29 16:46:28 -080011391 if ((r.serviceInfo.applicationInfo.flags
11392 &ApplicationInfo.FLAG_PERSISTENT) != 0) {
11393 // Services in peristent processes will restart much more
11394 // quickly, since they are pretty important. (Think SystemUI).
11395 r.restartDelay += minDuration/2;
11396 } else {
11397 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
11398 if (r.restartDelay < minDuration) {
11399 r.restartDelay = minDuration;
11400 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011402 }
11403 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011404
11405 r.nextRestartTime = now + r.restartDelay;
11406
11407 // Make sure that we don't end up restarting a bunch of services
11408 // all at the same time.
11409 boolean repeat;
11410 do {
11411 repeat = false;
11412 for (int i=mRestartingServices.size()-1; i>=0; i--) {
11413 ServiceRecord r2 = mRestartingServices.get(i);
11414 if (r2 != r && r.nextRestartTime
11415 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
11416 && r.nextRestartTime
11417 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
11418 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
11419 r.restartDelay = r.nextRestartTime - now;
11420 repeat = true;
11421 break;
11422 }
11423 }
11424 } while (repeat);
11425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011426 if (!mRestartingServices.contains(r)) {
11427 mRestartingServices.add(r);
11428 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011429
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011430 r.cancelNotification();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011432 mHandler.removeCallbacks(r.restarter);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070011433 mHandler.postAtTime(r.restarter, r.nextRestartTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011434 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011435 Slog.w(TAG, "Scheduling restart of crashed service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011436 + r.shortName + " in " + r.restartDelay + "ms");
Doug Zongker2bec3d42009-12-04 12:52:44 -080011437 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011438 r.shortName, r.restartDelay);
11439
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011440 return canceled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011441 }
11442
11443 final void performServiceRestartLocked(ServiceRecord r) {
11444 if (!mRestartingServices.contains(r)) {
11445 return;
11446 }
11447 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), true);
11448 }
11449
11450 private final boolean unscheduleServiceRestartLocked(ServiceRecord r) {
11451 if (r.restartDelay == 0) {
11452 return false;
11453 }
11454 r.resetRestartCounter();
11455 mRestartingServices.remove(r);
11456 mHandler.removeCallbacks(r.restarter);
11457 return true;
11458 }
11459
11460 private final boolean bringUpServiceLocked(ServiceRecord r,
11461 int intentFlags, boolean whileRestarting) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011462 //Slog.i(TAG, "Bring up service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011463 //r.dump(" ");
11464
Dianne Hackborn36124872009-10-08 16:22:03 -070011465 if (r.app != null && r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011466 sendServiceArgsLocked(r, false);
11467 return true;
11468 }
11469
11470 if (!whileRestarting && r.restartDelay > 0) {
11471 // If waiting for a restart, then do nothing.
11472 return true;
11473 }
11474
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011475 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing up " + r + " " + r.intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011476
Dianne Hackbornde42bb62009-08-05 12:26:15 -070011477 // We are now bringing the service up, so no longer in the
11478 // restarting state.
11479 mRestartingServices.remove(r);
11480
Dianne Hackborne7f97212011-02-24 14:40:20 -080011481 // Service is now being launched, its package can't be stopped.
11482 try {
11483 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011484 r.packageName, false, r.userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011485 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080011486 } catch (IllegalArgumentException e) {
11487 Slog.w(TAG, "Failed trying to unstop package "
11488 + r.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080011489 }
11490
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011491 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011492 final String appName = r.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011493 ProcessRecord app;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011494
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011495 if (!isolated) {
11496 app = getProcessRecordLocked(appName, r.appInfo.uid);
11497 if (DEBUG_MU)
11498 Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid + " app=" + app);
11499 if (app != null && app.thread != null) {
11500 try {
11501 app.addPackage(r.appInfo.packageName);
11502 realStartServiceLocked(r, app);
11503 return true;
11504 } catch (RemoteException e) {
11505 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
11506 }
11507
11508 // If a dead object exception was thrown -- fall through to
11509 // restart the application.
11510 }
11511 } else {
11512 // If this service runs in an isolated process, then each time
11513 // we call startProcessLocked() we will get a new isolated
11514 // process, starting another process if we are currently waiting
11515 // for a previous process to come up. To deal with this, we store
11516 // in the service any current isolated process it is running in or
11517 // waiting to have come up.
11518 app = r.isolatedProc;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011519 }
11520
Dianne Hackborn36124872009-10-08 16:22:03 -070011521 // Not running -- get it started, and enqueue this service record
11522 // to be executed when the app comes up.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011523 if (app == null) {
11524 if ((app=startProcessLocked(appName, r.appInfo, true, intentFlags,
11525 "service", r.name, false, isolated)) == null) {
11526 Slog.w(TAG, "Unable to launch app "
11527 + r.appInfo.packageName + "/"
11528 + r.appInfo.uid + " for service "
11529 + r.intent.getIntent() + ": process is bad");
11530 bringDownServiceLocked(r, true);
11531 return false;
11532 }
11533 if (isolated) {
11534 r.isolatedProc = app;
11535 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011536 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011538 if (!mPendingServices.contains(r)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011539 mPendingServices.add(r);
11540 }
Dianne Hackborn36124872009-10-08 16:22:03 -070011541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011542 return true;
11543 }
11544
11545 private final void bringDownServiceLocked(ServiceRecord r, boolean force) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011546 //Slog.i(TAG, "Bring down service:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011547 //r.dump(" ");
11548
11549 // Does it still need to run?
11550 if (!force && r.startRequested) {
11551 return;
11552 }
11553 if (r.connections.size() > 0) {
11554 if (!force) {
11555 // XXX should probably keep a count of the number of auto-create
11556 // connections directly in the service.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011557 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011558 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011559 ArrayList<ConnectionRecord> cr = it.next();
11560 for (int i=0; i<cr.size(); i++) {
11561 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
11562 return;
11563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011564 }
11565 }
11566 }
11567
11568 // Report to all of the connections that the service is no longer
11569 // available.
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011570 Iterator<ArrayList<ConnectionRecord>> it = r.connections.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011571 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011572 ArrayList<ConnectionRecord> c = it.next();
11573 for (int i=0; i<c.size(); i++) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011574 ConnectionRecord cr = c.get(i);
11575 // There is still a connection to the service that is
11576 // being brought down. Mark it as dead.
11577 cr.serviceDead = true;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011578 try {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070011579 cr.conn.connected(r.name, null);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011580 } catch (Exception e) {
11581 Slog.w(TAG, "Failure disconnecting service " + r.name +
11582 " to connection " + c.get(i).conn.asBinder() +
11583 " (in " + c.get(i).binding.client.processName + ")", e);
11584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011585 }
11586 }
11587 }
11588
11589 // Tell the service that it has been unbound.
11590 if (r.bindings.size() > 0 && r.app != null && r.app.thread != null) {
11591 Iterator<IntentBindRecord> it = r.bindings.values().iterator();
11592 while (it.hasNext()) {
11593 IntentBindRecord ibr = it.next();
Joe Onorato8a9b2202010-02-26 18:56:32 -080011594 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down binding " + ibr
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011595 + ": hasBound=" + ibr.hasBound);
11596 if (r.app != null && r.app.thread != null && ibr.hasBound) {
11597 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011598 bumpServiceExecutingLocked(r, "bring down unbind");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011599 updateOomAdjLocked(r.app);
11600 ibr.hasBound = false;
11601 r.app.thread.scheduleUnbindService(r,
11602 ibr.intent.getIntent());
11603 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011604 Slog.w(TAG, "Exception when unbinding service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011605 + r.shortName, e);
11606 serviceDoneExecutingLocked(r, true);
11607 }
11608 }
11609 }
11610 }
11611
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011612 if (DEBUG_SERVICE) Slog.v(TAG, "Bringing down " + r + " " + r.intent);
Doug Zongker2bec3d42009-12-04 12:52:44 -080011613 EventLog.writeEvent(EventLogTags.AM_DESTROY_SERVICE,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011614 System.identityHashCode(r), r.shortName,
11615 (r.app != null) ? r.app.pid : -1);
11616
Amith Yamasani742a6712011-05-04 14:49:28 -070011617 mServiceMap.removeServiceByName(r.name, r.userId);
11618 mServiceMap.removeServiceByIntent(r.intent, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011619 r.totalRestartCount = 0;
11620 unscheduleServiceRestartLocked(r);
11621
11622 // Also make sure it is not on the pending list.
11623 int N = mPendingServices.size();
11624 for (int i=0; i<N; i++) {
11625 if (mPendingServices.get(i) == r) {
11626 mPendingServices.remove(i);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011627 if (DEBUG_SERVICE) Slog.v(TAG, "Removed pending: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011628 i--;
11629 N--;
11630 }
11631 }
11632
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011633 r.cancelNotification();
11634 r.isForeground = false;
11635 r.foregroundId = 0;
11636 r.foregroundNoti = null;
11637
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011638 // Clear start entries.
Dianne Hackborn39792d22010-08-19 18:01:52 -070011639 r.clearDeliveredStartsLocked();
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011640 r.pendingStarts.clear();
11641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011642 if (r.app != null) {
11643 synchronized (r.stats.getBatteryStats()) {
11644 r.stats.stopLaunchedLocked();
11645 }
11646 r.app.services.remove(r);
11647 if (r.app.thread != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011648 try {
Dianne Hackborn287952c2010-09-22 22:34:31 -070011649 bumpServiceExecutingLocked(r, "stop");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011650 mStoppingServices.add(r);
11651 updateOomAdjLocked(r.app);
11652 r.app.thread.scheduleStopService(r);
11653 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011654 Slog.w(TAG, "Exception when stopping service "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011655 + r.shortName, e);
11656 serviceDoneExecutingLocked(r, true);
11657 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011658 updateServiceForegroundLocked(r.app, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011659 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011660 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011661 TAG, "Removed service that has no process: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011662 }
11663 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011664 if (DEBUG_SERVICE) Slog.v(
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011665 TAG, "Removed service that is not running: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011666 }
Vairavan Srinivasana207ce22010-12-23 13:51:48 -080011667
11668 if (r.bindings.size() > 0) {
11669 r.bindings.clear();
11670 }
11671
11672 if (r.restarter instanceof ServiceRestarter) {
11673 ((ServiceRestarter)r.restarter).setService(null);
11674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011675 }
11676
11677 ComponentName startServiceLocked(IApplicationThread caller,
11678 Intent service, String resolvedType,
11679 int callingPid, int callingUid) {
11680 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011681 if (DEBUG_SERVICE) Slog.v(TAG, "startService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011682 + " type=" + resolvedType + " args=" + service.getExtras());
11683
11684 if (caller != null) {
11685 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11686 if (callerApp == null) {
11687 throw new SecurityException(
11688 "Unable to find app for caller " + caller
11689 + " (pid=" + Binder.getCallingPid()
11690 + ") when starting service " + service);
11691 }
11692 }
11693
11694 ServiceLookupResult res =
11695 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011696 callingPid, callingUid, UserId.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011697 if (res == null) {
11698 return null;
11699 }
11700 if (res.record == null) {
11701 return new ComponentName("!", res.permission != null
11702 ? res.permission : "private to package");
11703 }
11704 ServiceRecord r = res.record;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011705 NeededUriGrants neededGrants = checkGrantUriPermissionFromIntentLocked(
11706 callingUid, r.packageName, service, service.getFlags(), null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011707 if (unscheduleServiceRestartLocked(r)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070011708 if (DEBUG_SERVICE) Slog.v(TAG, "START SERVICE WHILE RESTART PENDING: " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011709 }
11710 r.startRequested = true;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011711 r.callStart = false;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011712 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
Dianne Hackborn21c241e2012-03-08 13:57:23 -080011713 service, neededGrants));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011714 r.lastActivity = SystemClock.uptimeMillis();
11715 synchronized (r.stats.getBatteryStats()) {
11716 r.stats.startRunningLocked();
11717 }
11718 if (!bringUpServiceLocked(r, service.getFlags(), false)) {
11719 return new ComponentName("!", "Service process is bad");
11720 }
11721 return r.name;
11722 }
11723 }
11724
11725 public ComponentName startService(IApplicationThread caller, Intent service,
11726 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011727 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011728 // Refuse possible leaked file descriptors
11729 if (service != null && service.hasFileDescriptors() == true) {
11730 throw new IllegalArgumentException("File descriptors passed in Intent");
11731 }
11732
Amith Yamasani742a6712011-05-04 14:49:28 -070011733 if (DEBUG_SERVICE)
11734 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011735 synchronized(this) {
11736 final int callingPid = Binder.getCallingPid();
11737 final int callingUid = Binder.getCallingUid();
11738 final long origId = Binder.clearCallingIdentity();
11739 ComponentName res = startServiceLocked(caller, service,
11740 resolvedType, callingPid, callingUid);
11741 Binder.restoreCallingIdentity(origId);
11742 return res;
11743 }
11744 }
11745
11746 ComponentName startServiceInPackage(int uid,
11747 Intent service, String resolvedType) {
11748 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070011749 if (DEBUG_SERVICE)
11750 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011751 final long origId = Binder.clearCallingIdentity();
11752 ComponentName res = startServiceLocked(null, service,
11753 resolvedType, -1, uid);
11754 Binder.restoreCallingIdentity(origId);
11755 return res;
11756 }
11757 }
11758
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011759 private void stopServiceLocked(ServiceRecord service) {
11760 synchronized (service.stats.getBatteryStats()) {
11761 service.stats.stopRunningLocked();
11762 }
11763 service.startRequested = false;
11764 service.callStart = false;
11765 bringDownServiceLocked(service, false);
11766 }
11767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011768 public int stopService(IApplicationThread caller, Intent service,
11769 String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011770 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011771 // Refuse possible leaked file descriptors
11772 if (service != null && service.hasFileDescriptors() == true) {
11773 throw new IllegalArgumentException("File descriptors passed in Intent");
11774 }
11775
11776 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011777 if (DEBUG_SERVICE) Slog.v(TAG, "stopService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011778 + " type=" + resolvedType);
11779
11780 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11781 if (caller != null && callerApp == null) {
11782 throw new SecurityException(
11783 "Unable to find app for caller " + caller
11784 + " (pid=" + Binder.getCallingPid()
11785 + ") when stopping service " + service);
11786 }
11787
11788 // If this service is active, make sure it is stopped.
Amith Yamasani483f3b02012-03-13 16:08:00 -070011789 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11790 callerApp == null ? UserId.getCallingUserId() : callerApp.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011791 if (r != null) {
11792 if (r.record != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011793 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011794 try {
11795 stopServiceLocked(r.record);
11796 } finally {
11797 Binder.restoreCallingIdentity(origId);
11798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011799 return 1;
11800 }
11801 return -1;
11802 }
11803 }
11804
11805 return 0;
11806 }
11807
11808 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011809 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011810 // Refuse possible leaked file descriptors
11811 if (service != null && service.hasFileDescriptors() == true) {
11812 throw new IllegalArgumentException("File descriptors passed in Intent");
11813 }
11814
11815 IBinder ret = null;
11816
11817 synchronized(this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011818 ServiceLookupResult r = findServiceLocked(service, resolvedType,
11819 UserId.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011820
11821 if (r != null) {
11822 // r.record is null if findServiceLocked() failed the caller permission check
11823 if (r.record == null) {
11824 throw new SecurityException(
11825 "Permission Denial: Accessing service " + r.record.name
11826 + " from pid=" + Binder.getCallingPid()
11827 + ", uid=" + Binder.getCallingUid()
11828 + " requires " + r.permission);
11829 }
11830 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
11831 if (ib != null) {
11832 ret = ib.binder;
11833 }
11834 }
11835 }
11836
11837 return ret;
11838 }
11839
11840 public boolean stopServiceToken(ComponentName className, IBinder token,
11841 int startId) {
11842 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011843 if (DEBUG_SERVICE) Slog.v(TAG, "stopServiceToken: " + className
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011844 + " " + token + " startId=" + startId);
11845 ServiceRecord r = findServiceLocked(className, token);
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011846 if (r != null) {
11847 if (startId >= 0) {
11848 // Asked to only stop if done with all work. Note that
11849 // to avoid leaks, we will take this as dropping all
11850 // start items up to and including this one.
11851 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
11852 if (si != null) {
11853 while (r.deliveredStarts.size() > 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -070011854 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
11855 cur.removeUriPermissionsLocked();
11856 if (cur == si) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011857 break;
11858 }
11859 }
11860 }
11861
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070011862 if (r.getLastStartId() != startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011863 return false;
11864 }
11865
11866 if (r.deliveredStarts.size() > 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011867 Slog.w(TAG, "stopServiceToken startId " + startId
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011868 + " is last, but have " + r.deliveredStarts.size()
11869 + " remaining args");
11870 }
11871 }
11872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011873 synchronized (r.stats.getBatteryStats()) {
11874 r.stats.stopRunningLocked();
11875 r.startRequested = false;
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070011876 r.callStart = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011877 }
11878 final long origId = Binder.clearCallingIdentity();
11879 bringDownServiceLocked(r, false);
11880 Binder.restoreCallingIdentity(origId);
11881 return true;
11882 }
11883 }
11884 return false;
11885 }
11886
11887 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011888 int id, Notification notification, boolean removeNotification) {
11889 final long origId = Binder.clearCallingIdentity();
11890 try {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011891 synchronized(this) {
11892 ServiceRecord r = findServiceLocked(className, token);
11893 if (r != null) {
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011894 if (id != 0) {
11895 if (notification == null) {
11896 throw new IllegalArgumentException("null notification");
11897 }
11898 if (r.foregroundId != id) {
11899 r.cancelNotification();
11900 r.foregroundId = id;
11901 }
11902 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
11903 r.foregroundNoti = notification;
11904 r.isForeground = true;
11905 r.postNotification();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011906 if (r.app != null) {
11907 updateServiceForegroundLocked(r.app, true);
11908 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011909 } else {
11910 if (r.isForeground) {
11911 r.isForeground = false;
11912 if (r.app != null) {
Dianne Hackborn8633e682010-04-22 16:03:41 -070011913 updateLruProcessLocked(r.app, false, true);
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011914 updateServiceForegroundLocked(r.app, true);
11915 }
11916 }
11917 if (removeNotification) {
11918 r.cancelNotification();
11919 r.foregroundId = 0;
11920 r.foregroundNoti = null;
11921 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 }
11923 }
11924 }
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070011925 } finally {
11926 Binder.restoreCallingIdentity(origId);
11927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011928 }
11929
11930 public void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
11931 boolean anyForeground = false;
Dianne Hackborn860755f2010-06-03 18:47:52 -070011932 for (ServiceRecord sr : proc.services) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011933 if (sr.isForeground) {
11934 anyForeground = true;
11935 break;
11936 }
11937 }
11938 if (anyForeground != proc.foregroundServices) {
11939 proc.foregroundServices = anyForeground;
11940 if (oomAdj) {
11941 updateOomAdjLocked();
11942 }
11943 }
11944 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070011945
11946 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo) {
11947 boolean result = false;
11948 if (UserId.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
11949 result = false;
11950 } else if (componentProcessName == aInfo.packageName) {
11951 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
11952 } else if ("system".equals(componentProcessName)) {
11953 result = true;
11954 }
11955 if (DEBUG_MU) {
11956 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo + ") = " + result);
11957 }
11958 return result;
11959 }
11960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011961 public int bindService(IApplicationThread caller, IBinder token,
11962 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011963 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011964 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011965 // Refuse possible leaked file descriptors
11966 if (service != null && service.hasFileDescriptors() == true) {
11967 throw new IllegalArgumentException("File descriptors passed in Intent");
11968 }
11969
Amith Yamasani37ce3a82012-02-06 12:04:42 -080011970 checkValidCaller(Binder.getCallingUid(), userId);
11971
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011972 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011973 if (DEBUG_SERVICE) Slog.v(TAG, "bindService: " + service
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011974 + " type=" + resolvedType + " conn=" + connection.asBinder()
11975 + " flags=0x" + Integer.toHexString(flags));
Amith Yamasani742a6712011-05-04 14:49:28 -070011976 if (DEBUG_MU)
11977 Slog.i(TAG_MU, "bindService uid=" + Binder.getCallingUid() + " origUid="
11978 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011979 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11980 if (callerApp == null) {
11981 throw new SecurityException(
11982 "Unable to find app for caller " + caller
11983 + " (pid=" + Binder.getCallingPid()
11984 + ") when binding service " + service);
11985 }
11986
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070011987 ActivityRecord activity = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011988 if (token != null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070011989 activity = mMainStack.isInStackLocked(token);
11990 if (activity == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011991 Slog.w(TAG, "Binding with unknown activity: " + token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011992 return 0;
11993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011994 }
11995
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070011996 int clientLabel = 0;
11997 PendingIntent clientIntent = null;
11998
11999 if (callerApp.info.uid == Process.SYSTEM_UID) {
12000 // Hacky kind of thing -- allow system stuff to tell us
12001 // what they are, so we can report this elsewhere for
12002 // others to know why certain services are running.
12003 try {
12004 clientIntent = (PendingIntent)service.getParcelableExtra(
12005 Intent.EXTRA_CLIENT_INTENT);
12006 } catch (RuntimeException e) {
12007 }
12008 if (clientIntent != null) {
12009 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
12010 if (clientLabel != 0) {
12011 // There are no useful extras in the intent, trash them.
12012 // System code calling with this stuff just needs to know
12013 // this will happen.
12014 service = service.cloneFilter();
12015 }
12016 }
12017 }
12018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012019 ServiceLookupResult res =
12020 retrieveServiceLocked(service, resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080012021 Binder.getCallingPid(), Binder.getCallingUid(), userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012022 if (res == null) {
12023 return 0;
12024 }
12025 if (res.record == null) {
12026 return -1;
12027 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070012028 if (isSingleton(res.record.processName, res.record.appInfo)) {
12029 userId = 0;
12030 res = retrieveServiceLocked(service, resolvedType, Binder.getCallingPid(),
12031 Binder.getCallingUid(), 0);
12032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012033 ServiceRecord s = res.record;
12034
12035 final long origId = Binder.clearCallingIdentity();
12036
12037 if (unscheduleServiceRestartLocked(s)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012038 if (DEBUG_SERVICE) Slog.v(TAG, "BIND SERVICE WHILE RESTART PENDING: "
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012039 + s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012040 }
12041
12042 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
12043 ConnectionRecord c = new ConnectionRecord(b, activity,
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070012044 connection, flags, clientLabel, clientIntent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012045
12046 IBinder binder = connection.asBinder();
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012047 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12048 if (clist == null) {
12049 clist = new ArrayList<ConnectionRecord>();
12050 s.connections.put(binder, clist);
12051 }
12052 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012053 b.connections.add(c);
12054 if (activity != null) {
12055 if (activity.connections == null) {
12056 activity.connections = new HashSet<ConnectionRecord>();
12057 }
12058 activity.connections.add(c);
12059 }
12060 b.client.connections.add(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012061 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12062 b.client.hasAboveClient = true;
12063 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012064 clist = mServiceConnections.get(binder);
12065 if (clist == null) {
12066 clist = new ArrayList<ConnectionRecord>();
12067 mServiceConnections.put(binder, clist);
12068 }
12069 clist.add(c);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012070
12071 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
12072 s.lastActivity = SystemClock.uptimeMillis();
12073 if (!bringUpServiceLocked(s, service.getFlags(), false)) {
12074 return 0;
12075 }
12076 }
12077
12078 if (s.app != null) {
12079 // This could have made the service more important.
12080 updateOomAdjLocked(s.app);
12081 }
12082
Joe Onorato8a9b2202010-02-26 18:56:32 -080012083 if (DEBUG_SERVICE) Slog.v(TAG, "Bind " + s + " with " + b
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012084 + ": received=" + b.intent.received
12085 + " apps=" + b.intent.apps.size()
12086 + " doRebind=" + b.intent.doRebind);
12087
12088 if (s.app != null && b.intent.received) {
12089 // Service is already running, so we can immediately
12090 // publish the connection.
12091 try {
12092 c.conn.connected(s.name, b.intent.binder);
12093 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012094 Slog.w(TAG, "Failure sending service " + s.shortName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012095 + " to connection " + c.conn.asBinder()
12096 + " (in " + c.binding.client.processName + ")", e);
12097 }
12098
12099 // If this is the first app connected back to this binding,
12100 // and the service had previously asked to be told when
12101 // rebound, then do so.
12102 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
12103 requestServiceBindingLocked(s, b.intent, true);
12104 }
12105 } else if (!b.intent.requested) {
12106 requestServiceBindingLocked(s, b.intent, false);
12107 }
12108
12109 Binder.restoreCallingIdentity(origId);
12110 }
12111
12112 return 1;
12113 }
12114
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012115 void removeConnectionLocked(
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012116 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012117 IBinder binder = c.conn.asBinder();
12118 AppBindRecord b = c.binding;
12119 ServiceRecord s = b.service;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012120 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
12121 if (clist != null) {
12122 clist.remove(c);
12123 if (clist.size() == 0) {
12124 s.connections.remove(binder);
12125 }
12126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012127 b.connections.remove(c);
12128 if (c.activity != null && c.activity != skipAct) {
12129 if (c.activity.connections != null) {
12130 c.activity.connections.remove(c);
12131 }
12132 }
12133 if (b.client != skipApp) {
12134 b.client.connections.remove(c);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012135 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
12136 b.client.updateHasAboveClientLocked();
12137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012138 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012139 clist = mServiceConnections.get(binder);
12140 if (clist != null) {
12141 clist.remove(c);
12142 if (clist.size() == 0) {
12143 mServiceConnections.remove(binder);
12144 }
12145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012146
12147 if (b.connections.size() == 0) {
12148 b.intent.apps.remove(b.client);
12149 }
12150
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012151 if (!c.serviceDead) {
12152 if (DEBUG_SERVICE) Slog.v(TAG, "Disconnecting binding " + b.intent
12153 + ": shouldUnbind=" + b.intent.hasBound);
12154 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
12155 && b.intent.hasBound) {
12156 try {
12157 bumpServiceExecutingLocked(s, "unbind");
12158 updateOomAdjLocked(s.app);
12159 b.intent.hasBound = false;
12160 // Assume the client doesn't want to know about a rebind;
12161 // we will deal with that later if it asks for one.
12162 b.intent.doRebind = false;
12163 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
12164 } catch (Exception e) {
12165 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
12166 serviceDoneExecutingLocked(s, true);
12167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012168 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012169
12170 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
12171 bringDownServiceLocked(s, false);
12172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012173 }
12174 }
12175
12176 public boolean unbindService(IServiceConnection connection) {
12177 synchronized (this) {
12178 IBinder binder = connection.asBinder();
Joe Onorato8a9b2202010-02-26 18:56:32 -080012179 if (DEBUG_SERVICE) Slog.v(TAG, "unbindService: conn=" + binder);
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012180 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
12181 if (clist == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012182 Slog.w(TAG, "Unbind failed: could not find connection for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012183 + connection.asBinder());
12184 return false;
12185 }
12186
12187 final long origId = Binder.clearCallingIdentity();
12188
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012189 while (clist.size() > 0) {
12190 ConnectionRecord r = clist.get(0);
12191 removeConnectionLocked(r, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012192
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012193 if (r.binding.service.app != null) {
12194 // This could have made the service less important.
12195 updateOomAdjLocked(r.binding.service.app);
12196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012197 }
12198
12199 Binder.restoreCallingIdentity(origId);
12200 }
12201
12202 return true;
12203 }
12204
12205 public void publishService(IBinder token, Intent intent, IBinder service) {
12206 // Refuse possible leaked file descriptors
12207 if (intent != null && intent.hasFileDescriptors() == true) {
12208 throw new IllegalArgumentException("File descriptors passed in Intent");
12209 }
12210
12211 synchronized(this) {
12212 if (!(token instanceof ServiceRecord)) {
12213 throw new IllegalArgumentException("Invalid service token");
12214 }
12215 ServiceRecord r = (ServiceRecord)token;
12216
12217 final long origId = Binder.clearCallingIdentity();
12218
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012219 if (DEBUG_SERVICE) Slog.v(TAG, "PUBLISHING " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012220 + " " + intent + ": " + service);
12221 if (r != null) {
12222 Intent.FilterComparison filter
12223 = new Intent.FilterComparison(intent);
12224 IntentBindRecord b = r.bindings.get(filter);
12225 if (b != null && !b.received) {
12226 b.binder = service;
12227 b.requested = true;
12228 b.received = true;
12229 if (r.connections.size() > 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012230 Iterator<ArrayList<ConnectionRecord>> it
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012231 = r.connections.values().iterator();
12232 while (it.hasNext()) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012233 ArrayList<ConnectionRecord> clist = it.next();
12234 for (int i=0; i<clist.size(); i++) {
12235 ConnectionRecord c = clist.get(i);
12236 if (!filter.equals(c.binding.intent.intent)) {
12237 if (DEBUG_SERVICE) Slog.v(
12238 TAG, "Not publishing to: " + c);
12239 if (DEBUG_SERVICE) Slog.v(
12240 TAG, "Bound intent: " + c.binding.intent.intent);
12241 if (DEBUG_SERVICE) Slog.v(
12242 TAG, "Published intent: " + intent);
12243 continue;
12244 }
12245 if (DEBUG_SERVICE) Slog.v(TAG, "Publishing to: " + c);
12246 try {
12247 c.conn.connected(r.name, service);
12248 } catch (Exception e) {
12249 Slog.w(TAG, "Failure sending service " + r.name +
12250 " to connection " + c.conn.asBinder() +
12251 " (in " + c.binding.client.processName + ")", e);
12252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012253 }
12254 }
12255 }
12256 }
12257
12258 serviceDoneExecutingLocked(r, mStoppingServices.contains(r));
12259
12260 Binder.restoreCallingIdentity(origId);
12261 }
12262 }
12263 }
12264
12265 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
12266 // Refuse possible leaked file descriptors
12267 if (intent != null && intent.hasFileDescriptors() == true) {
12268 throw new IllegalArgumentException("File descriptors passed in Intent");
12269 }
12270
12271 synchronized(this) {
12272 if (!(token instanceof ServiceRecord)) {
12273 throw new IllegalArgumentException("Invalid service token");
12274 }
12275 ServiceRecord r = (ServiceRecord)token;
12276
12277 final long origId = Binder.clearCallingIdentity();
12278
12279 if (r != null) {
12280 Intent.FilterComparison filter
12281 = new Intent.FilterComparison(intent);
12282 IntentBindRecord b = r.bindings.get(filter);
Joe Onorato8a9b2202010-02-26 18:56:32 -080012283 if (DEBUG_SERVICE) Slog.v(TAG, "unbindFinished in " + r
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012284 + " at " + b + ": apps="
12285 + (b != null ? b.apps.size() : 0));
Per Edelberg78f9fff2010-08-30 20:01:35 +020012286
12287 boolean inStopping = mStoppingServices.contains(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012288 if (b != null) {
Per Edelberg78f9fff2010-08-30 20:01:35 +020012289 if (b.apps.size() > 0 && !inStopping) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012290 // Applications have already bound since the last
12291 // unbind, so just rebind right here.
12292 requestServiceBindingLocked(r, b, true);
12293 } else {
12294 // Note to tell the service the next time there is
12295 // a new client.
12296 b.doRebind = true;
12297 }
12298 }
12299
Per Edelberg78f9fff2010-08-30 20:01:35 +020012300 serviceDoneExecutingLocked(r, inStopping);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012301
12302 Binder.restoreCallingIdentity(origId);
12303 }
12304 }
12305 }
12306
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012307 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012308 synchronized(this) {
12309 if (!(token instanceof ServiceRecord)) {
12310 throw new IllegalArgumentException("Invalid service token");
12311 }
12312 ServiceRecord r = (ServiceRecord)token;
12313 boolean inStopping = mStoppingServices.contains(token);
12314 if (r != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012315 if (r != token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012316 Slog.w(TAG, "Done executing service " + r.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012317 + " with incorrect token: given " + token
12318 + ", expected " + r);
12319 return;
12320 }
12321
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012322 if (type == 1) {
12323 // This is a call from a service start... take care of
12324 // book-keeping.
12325 r.callStart = true;
12326 switch (res) {
12327 case Service.START_STICKY_COMPATIBILITY:
12328 case Service.START_STICKY: {
12329 // We are done with the associated start arguments.
12330 r.findDeliveredStart(startId, true);
12331 // Don't stop if killed.
12332 r.stopIfKilled = false;
12333 break;
12334 }
12335 case Service.START_NOT_STICKY: {
12336 // We are done with the associated start arguments.
12337 r.findDeliveredStart(startId, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012338 if (r.getLastStartId() == startId) {
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012339 // There is no more work, and this service
12340 // doesn't want to hang around if killed.
12341 r.stopIfKilled = true;
12342 }
12343 break;
12344 }
12345 case Service.START_REDELIVER_INTENT: {
12346 // We'll keep this item until they explicitly
12347 // call stop for it, but keep track of the fact
12348 // that it was delivered.
12349 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
12350 if (si != null) {
12351 si.deliveryCount = 0;
12352 si.doneExecutingCount++;
12353 // Don't stop if killed.
12354 r.stopIfKilled = true;
12355 }
12356 break;
12357 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070012358 case Service.START_TASK_REMOVED_COMPLETE: {
12359 // Special processing for onTaskRemoved(). Don't
12360 // impact normal onStartCommand() processing.
12361 r.findDeliveredStart(startId, true);
12362 break;
12363 }
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070012364 default:
12365 throw new IllegalArgumentException(
12366 "Unknown service start result: " + res);
12367 }
12368 if (res == Service.START_STICKY_COMPATIBILITY) {
12369 r.callStart = false;
12370 }
12371 }
Amith Yamasani742a6712011-05-04 14:49:28 -070012372 if (DEBUG_MU)
12373 Slog.v(TAG_MU, "before serviceDontExecutingLocked, uid="
12374 + Binder.getOrigCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012375 final long origId = Binder.clearCallingIdentity();
12376 serviceDoneExecutingLocked(r, inStopping);
12377 Binder.restoreCallingIdentity(origId);
12378 } else {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012379 Slog.w(TAG, "Done executing unknown service from pid "
12380 + Binder.getCallingPid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012381 }
12382 }
12383 }
12384
12385 public void serviceDoneExecutingLocked(ServiceRecord r, boolean inStopping) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012386 if (DEBUG_SERVICE) Slog.v(TAG, "<<< DONE EXECUTING " + r
12387 + ": nesting=" + r.executeNesting
12388 + ", inStopping=" + inStopping + ", app=" + r.app);
Dianne Hackborn287952c2010-09-22 22:34:31 -070012389 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG, "<<< DONE EXECUTING " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012390 r.executeNesting--;
12391 if (r.executeNesting <= 0 && r.app != null) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012392 if (DEBUG_SERVICE) Slog.v(TAG,
12393 "Nesting at 0 of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012394 r.app.executingServices.remove(r);
12395 if (r.app.executingServices.size() == 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012396 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG,
12397 "No more executingServices of " + r.shortName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012398 mHandler.removeMessages(SERVICE_TIMEOUT_MSG, r.app);
12399 }
12400 if (inStopping) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012401 if (DEBUG_SERVICE) Slog.v(TAG,
12402 "doneExecuting remove stopping " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012403 mStoppingServices.remove(r);
Mattias Petersson3996b412010-10-27 09:32:51 +020012404 r.bindings.clear();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012405 }
12406 updateOomAdjLocked(r.app);
12407 }
12408 }
12409
12410 void serviceTimeout(ProcessRecord proc) {
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012411 String anrMessage = null;
12412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012413 synchronized(this) {
12414 if (proc.executingServices.size() == 0 || proc.thread == null) {
12415 return;
12416 }
12417 long maxTime = SystemClock.uptimeMillis() - SERVICE_TIMEOUT;
12418 Iterator<ServiceRecord> it = proc.executingServices.iterator();
12419 ServiceRecord timeout = null;
12420 long nextTime = 0;
12421 while (it.hasNext()) {
12422 ServiceRecord sr = it.next();
12423 if (sr.executingStart < maxTime) {
12424 timeout = sr;
12425 break;
12426 }
12427 if (sr.executingStart > nextTime) {
12428 nextTime = sr.executingStart;
12429 }
12430 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012431 if (timeout != null && mLruProcesses.contains(proc)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012432 Slog.w(TAG, "Timeout executing service: " + timeout);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012433 anrMessage = "Executing service " + timeout.shortName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012434 } else {
12435 Message msg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
12436 msg.obj = proc;
12437 mHandler.sendMessageAtTime(msg, nextTime+SERVICE_TIMEOUT);
12438 }
12439 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -070012440
12441 if (anrMessage != null) {
12442 appNotResponding(proc, null, null, anrMessage);
12443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012444 }
12445
12446 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070012447 // BACKUP AND RESTORE
12448 // =========================================================
12449
12450 // Cause the target app to be launched if necessary and its backup agent
12451 // instantiated. The backup agent will invoke backupAgentCreated() on the
12452 // activity manager to announce its creation.
12453 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012454 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012455 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
12456
12457 synchronized(this) {
12458 // !!! TODO: currently no check here that we're already bound
12459 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
12460 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
12461 synchronized (stats) {
12462 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
12463 }
12464
Dianne Hackborne7f97212011-02-24 14:40:20 -080012465 // Backup agent is now in use, its package can't be stopped.
12466 try {
12467 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012468 app.packageName, false, UserId.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080012469 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080012470 } catch (IllegalArgumentException e) {
12471 Slog.w(TAG, "Failed trying to unstop package "
12472 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080012473 }
12474
Christopher Tate181fafa2009-05-14 11:12:14 -070012475 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070012476 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
12477 ? new ComponentName(app.packageName, app.backupAgentName)
12478 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070012479 // startProcessLocked() returns existing proc's record if it's already running
12480 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080012481 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070012482 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012483 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070012484 return false;
12485 }
12486
12487 r.app = proc;
12488 mBackupTarget = r;
12489 mBackupAppName = app.packageName;
12490
Christopher Tate6fa95972009-06-05 18:43:55 -070012491 // Try not to kill the process during backup
12492 updateOomAdjLocked(proc);
12493
Christopher Tate181fafa2009-05-14 11:12:14 -070012494 // If the process is already attached, schedule the creation of the backup agent now.
12495 // If it is not yet live, this will be done when it attaches to the framework.
12496 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012497 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070012498 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012499 proc.thread.scheduleCreateBackupAgent(app,
12500 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070012501 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070012502 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070012503 }
12504 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012505 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070012506 }
12507 // Invariants: at this point, the target app process exists and the application
12508 // is either already running or in the process of coming up. mBackupTarget and
12509 // mBackupAppName describe the app, so that when it binds back to the AM we
12510 // know that it's scheduled for a backup-agent operation.
12511 }
12512
12513 return true;
12514 }
12515
12516 // A backup agent has just come up
12517 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012518 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070012519 + " = " + agent);
12520
12521 synchronized(this) {
12522 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012523 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070012524 return;
12525 }
Dianne Hackborn06740692010-09-22 22:46:21 -070012526 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012527
Dianne Hackborn06740692010-09-22 22:46:21 -070012528 long oldIdent = Binder.clearCallingIdentity();
12529 try {
12530 IBackupManager bm = IBackupManager.Stub.asInterface(
12531 ServiceManager.getService(Context.BACKUP_SERVICE));
12532 bm.agentConnected(agentPackageName, agent);
12533 } catch (RemoteException e) {
12534 // can't happen; the backup manager service is local
12535 } catch (Exception e) {
12536 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
12537 e.printStackTrace();
12538 } finally {
12539 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070012540 }
12541 }
12542
12543 // done with this agent
12544 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012545 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070012546 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012547 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070012548 return;
12549 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012550
12551 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070012552 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012553 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070012554 return;
12555 }
12556
Christopher Tate181fafa2009-05-14 11:12:14 -070012557 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012558 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070012559 return;
12560 }
12561
Christopher Tate6fa95972009-06-05 18:43:55 -070012562 ProcessRecord proc = mBackupTarget.app;
12563 mBackupTarget = null;
12564 mBackupAppName = null;
12565
12566 // Not backing this app up any more; reset its OOM adjustment
12567 updateOomAdjLocked(proc);
12568
Christopher Tatec7b31e32009-06-10 15:49:30 -070012569 // If the app crashed during backup, 'thread' will be null here
12570 if (proc.thread != null) {
12571 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040012572 proc.thread.scheduleDestroyBackupAgent(appInfo,
12573 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070012574 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012575 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070012576 e.printStackTrace();
12577 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012578 }
Christopher Tate181fafa2009-05-14 11:12:14 -070012579 }
12580 }
12581 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012582 // BROADCASTS
12583 // =========================================================
12584
Josh Bartel7f208742010-02-25 11:01:44 -060012585 private final List getStickiesLocked(String action, IntentFilter filter,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012586 List cur) {
12587 final ContentResolver resolver = mContext.getContentResolver();
12588 final ArrayList<Intent> list = mStickyBroadcasts.get(action);
12589 if (list == null) {
12590 return cur;
12591 }
12592 int N = list.size();
12593 for (int i=0; i<N; i++) {
12594 Intent intent = list.get(i);
12595 if (filter.match(resolver, intent, true, TAG) >= 0) {
12596 if (cur == null) {
12597 cur = new ArrayList<Intent>();
12598 }
12599 cur.add(intent);
12600 }
12601 }
12602 return cur;
12603 }
12604
Christopher Tatef46723b2012-01-26 14:19:24 -080012605 boolean isPendingBroadcastProcessLocked(int pid) {
12606 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
12607 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
12608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012609
Christopher Tatef46723b2012-01-26 14:19:24 -080012610 void skipPendingBroadcastLocked(int pid) {
12611 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
12612 for (BroadcastQueue queue : mBroadcastQueues) {
12613 queue.skipPendingBroadcastLocked(pid);
12614 }
12615 }
12616
12617 // The app just attached; send any pending broadcasts that it should receive
12618 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
12619 boolean didSomething = false;
12620 for (BroadcastQueue queue : mBroadcastQueues) {
12621 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012622 }
Christopher Tatef46723b2012-01-26 14:19:24 -080012623 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012624 }
12625
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012626 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012627 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012628 enforceNotIsolatedCaller("registerReceiver");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 synchronized(this) {
12630 ProcessRecord callerApp = null;
12631 if (caller != null) {
12632 callerApp = getRecordForAppLocked(caller);
12633 if (callerApp == null) {
12634 throw new SecurityException(
12635 "Unable to find app for caller " + caller
12636 + " (pid=" + Binder.getCallingPid()
12637 + ") when registering receiver " + receiver);
12638 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012639 if (callerApp.info.uid != Process.SYSTEM_UID &&
12640 !callerApp.pkgList.contains(callerPackage)) {
12641 throw new SecurityException("Given caller package " + callerPackage
12642 + " is not running in process " + callerApp);
12643 }
12644 } else {
12645 callerPackage = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012646 }
12647
12648 List allSticky = null;
12649
12650 // Look for any matching sticky broadcasts...
12651 Iterator actions = filter.actionsIterator();
12652 if (actions != null) {
12653 while (actions.hasNext()) {
12654 String action = (String)actions.next();
Josh Bartel7f208742010-02-25 11:01:44 -060012655 allSticky = getStickiesLocked(action, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012656 }
12657 } else {
Josh Bartel7f208742010-02-25 11:01:44 -060012658 allSticky = getStickiesLocked(null, filter, allSticky);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012659 }
12660
12661 // The first sticky in the list is returned directly back to
12662 // the client.
12663 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
12664
Joe Onorato8a9b2202010-02-26 18:56:32 -080012665 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012666 + ": " + sticky);
12667
12668 if (receiver == null) {
12669 return sticky;
12670 }
12671
12672 ReceiverList rl
12673 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
12674 if (rl == null) {
12675 rl = new ReceiverList(this, callerApp,
12676 Binder.getCallingPid(),
12677 Binder.getCallingUid(), receiver);
12678 if (rl.app != null) {
12679 rl.app.receivers.add(rl);
12680 } else {
12681 try {
12682 receiver.asBinder().linkToDeath(rl, 0);
12683 } catch (RemoteException e) {
12684 return sticky;
12685 }
12686 rl.linkedToDeath = true;
12687 }
12688 mRegisteredReceivers.put(receiver.asBinder(), rl);
12689 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070012690 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, permission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012691 rl.add(bf);
12692 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012693 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012694 }
12695 mReceiverResolver.addFilter(bf);
12696
12697 // Enqueue broadcasts for all existing stickies that match
12698 // this filter.
12699 if (allSticky != null) {
12700 ArrayList receivers = new ArrayList();
12701 receivers.add(bf);
12702
12703 int N = allSticky.size();
12704 for (int i=0; i<N; i++) {
12705 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080012706 BroadcastQueue queue = broadcastQueueForIntent(intent);
12707 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012708 null, -1, -1, null, receivers, null, 0, null, null,
Dianne Hackborn12527f92009-11-11 17:39:50 -080012709 false, true, true);
Christopher Tatef46723b2012-01-26 14:19:24 -080012710 queue.enqueueParallelBroadcastLocked(r);
12711 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012712 }
12713 }
12714
12715 return sticky;
12716 }
12717 }
12718
12719 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012720 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012721
Christopher Tatef46723b2012-01-26 14:19:24 -080012722 final long origId = Binder.clearCallingIdentity();
12723 try {
12724 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012725
Christopher Tatef46723b2012-01-26 14:19:24 -080012726 synchronized(this) {
12727 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012728 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080012729 if (rl != null) {
12730 if (rl.curBroadcast != null) {
12731 BroadcastRecord r = rl.curBroadcast;
12732 final boolean doNext = finishReceiverLocked(
12733 receiver.asBinder(), r.resultCode, r.resultData,
12734 r.resultExtras, r.resultAbort, true);
12735 if (doNext) {
12736 doTrim = true;
12737 r.queue.processNextBroadcast(false);
12738 }
12739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012740
Christopher Tatef46723b2012-01-26 14:19:24 -080012741 if (rl.app != null) {
12742 rl.app.receivers.remove(rl);
12743 }
12744 removeReceiverLocked(rl);
12745 if (rl.linkedToDeath) {
12746 rl.linkedToDeath = false;
12747 rl.receiver.asBinder().unlinkToDeath(rl, 0);
12748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012749 }
12750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012751
Christopher Tatef46723b2012-01-26 14:19:24 -080012752 // If we actually concluded any broadcasts, we might now be able
12753 // to trim the recipients' apps from our working set
12754 if (doTrim) {
12755 trimApplications();
12756 return;
12757 }
12758
12759 } finally {
12760 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012761 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012762 }
12763
12764 void removeReceiverLocked(ReceiverList rl) {
12765 mRegisteredReceivers.remove(rl.receiver.asBinder());
12766 int N = rl.size();
12767 for (int i=0; i<N; i++) {
12768 mReceiverResolver.removeFilter(rl.get(i));
12769 }
12770 }
12771
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012772 private final void sendPackageBroadcastLocked(int cmd, String[] packages) {
12773 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
12774 ProcessRecord r = mLruProcesses.get(i);
12775 if (r.thread != null) {
12776 try {
12777 r.thread.dispatchPackageBroadcast(cmd, packages);
12778 } catch (RemoteException ex) {
12779 }
12780 }
12781 }
12782 }
12783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012784 private final int broadcastIntentLocked(ProcessRecord callerApp,
12785 String callerPackage, Intent intent, String resolvedType,
12786 IIntentReceiver resultTo, int resultCode, String resultData,
12787 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070012788 boolean ordered, boolean sticky, int callingPid, int callingUid,
12789 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012790 intent = new Intent(intent);
12791
Dianne Hackborne7f97212011-02-24 14:40:20 -080012792 // By default broadcasts do not go to stopped apps.
12793 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
12794
Joe Onorato8a9b2202010-02-26 18:56:32 -080012795 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012796 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070012797 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012798 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012799 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012800 }
12801
12802 // Handle special intents: if this broadcast is from the package
12803 // manager about a package being removed, we need to remove all of
12804 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012805 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012806 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012807 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
12808 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012809 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012810 || uidRemoved) {
12811 if (checkComponentPermission(
12812 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080012813 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012814 == PackageManager.PERMISSION_GRANTED) {
12815 if (uidRemoved) {
12816 final Bundle intentExtras = intent.getExtras();
12817 final int uid = intentExtras != null
12818 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
12819 if (uid >= 0) {
12820 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
12821 synchronized (bs) {
12822 bs.removeUidStatsLocked(uid);
12823 }
12824 }
12825 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012826 // If resources are unvailble just force stop all
12827 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080012828 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012829 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
12830 if (list != null && (list.length > 0)) {
12831 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070012832 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012833 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012834 sendPackageBroadcastLocked(
12835 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080012836 }
12837 } else {
12838 Uri data = intent.getData();
12839 String ssp;
12840 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12841 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
12842 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070012843 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
12844 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070012845 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012846 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070012847 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
12848 new String[] {ssp});
12849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012850 }
12851 }
12852 }
12853 } else {
12854 String msg = "Permission Denial: " + intent.getAction()
12855 + " broadcast from " + callerPackage + " (pid=" + callingPid
12856 + ", uid=" + callingUid + ")"
12857 + " requires "
12858 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012859 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012860 throw new SecurityException(msg);
12861 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012862
12863 // Special case for adding a package: by default turn on compatibility
12864 // mode.
12865 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070012866 Uri data = intent.getData();
12867 String ssp;
12868 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
12869 mCompatModePackages.handlePackageAddedLocked(ssp,
12870 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070012871 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012872 }
12873
12874 /*
12875 * If this is the time zone changed action, queue up a message that will reset the timezone
12876 * of all currently running processes. This message will get queued up before the broadcast
12877 * happens.
12878 */
12879 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
12880 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
12881 }
12882
Robert Greenwalt03595d02010-11-02 14:08:23 -070012883 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
12884 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
12885 }
12886
Robert Greenwalt434203a2010-10-11 16:00:27 -070012887 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
12888 ProxyProperties proxy = intent.getParcelableExtra("proxy");
12889 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
12890 }
12891
Dianne Hackborn854060af2009-07-09 18:14:31 -070012892 /*
12893 * Prevent non-system code (defined here to be non-persistent
12894 * processes) from sending protected broadcasts.
12895 */
12896 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
12897 || callingUid == Process.SHELL_UID || callingUid == 0) {
12898 // Always okay.
12899 } else if (callerApp == null || !callerApp.persistent) {
12900 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012901 if (AppGlobals.getPackageManager().isProtectedBroadcast(
Dianne Hackborn854060af2009-07-09 18:14:31 -070012902 intent.getAction())) {
12903 String msg = "Permission Denial: not allowed to send broadcast "
12904 + intent.getAction() + " from pid="
12905 + callingPid + ", uid=" + callingUid;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012906 Slog.w(TAG, msg);
Dianne Hackborn854060af2009-07-09 18:14:31 -070012907 throw new SecurityException(msg);
12908 }
12909 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012910 Slog.w(TAG, "Remote exception", e);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012911 return ActivityManager.BROADCAST_SUCCESS;
Dianne Hackborn854060af2009-07-09 18:14:31 -070012912 }
12913 }
12914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012915 // Add to the sticky list if requested.
12916 if (sticky) {
12917 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
12918 callingPid, callingUid)
12919 != PackageManager.PERMISSION_GRANTED) {
12920 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
12921 + callingPid + ", uid=" + callingUid
12922 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012923 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012924 throw new SecurityException(msg);
12925 }
12926 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012927 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012928 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070012929 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012930 }
12931 if (intent.getComponent() != null) {
12932 throw new SecurityException(
12933 "Sticky broadcasts can't target a specific component");
12934 }
12935 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
12936 if (list == null) {
12937 list = new ArrayList<Intent>();
12938 mStickyBroadcasts.put(intent.getAction(), list);
12939 }
12940 int N = list.size();
12941 int i;
12942 for (i=0; i<N; i++) {
12943 if (intent.filterEquals(list.get(i))) {
12944 // This sticky already exists, replace it.
12945 list.set(i, new Intent(intent));
12946 break;
12947 }
12948 }
12949 if (i >= N) {
12950 list.add(new Intent(intent));
12951 }
12952 }
12953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012954 // Figure out who all will receive this broadcast.
12955 List receivers = null;
12956 List<BroadcastFilter> registeredReceivers = null;
12957 try {
12958 if (intent.getComponent() != null) {
12959 // Broadcast is going to one specific receiver class...
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012960 ActivityInfo ai = AppGlobals.getPackageManager().
Amith Yamasani483f3b02012-03-13 16:08:00 -070012961 getReceiverInfo(intent.getComponent(), STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012962 if (ai != null) {
12963 receivers = new ArrayList();
12964 ResolveInfo ri = new ResolveInfo();
Amith Yamasania4a54e22012-04-16 15:44:19 -070012965 if (isSingleton(ai.processName, ai.applicationInfo)) {
12966 ri.activityInfo = getActivityInfoForUser(ai, 0);
12967 } else {
12968 ri.activityInfo = getActivityInfoForUser(ai, userId);
12969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012970 receivers.add(ri);
12971 }
12972 } else {
12973 // Need to resolve the intent to interested receivers...
12974 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
12975 == 0) {
12976 receivers =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070012977 AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -070012978 intent, resolvedType, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012979 }
Amith Yamasani483f3b02012-03-13 16:08:00 -070012980 registeredReceivers = mReceiverResolver.queryIntent(intent, resolvedType, false,
12981 userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012982 }
12983 } catch (RemoteException ex) {
12984 // pm is in same process, this will never happen.
12985 }
12986
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012987 final boolean replacePending =
12988 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
12989
Joe Onorato8a9b2202010-02-26 18:56:32 -080012990 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012991 + " replacePending=" + replacePending);
12992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012993 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
12994 if (!ordered && NR > 0) {
12995 // If we are not serializing this broadcast, then send the
12996 // registered receivers separately so they don't wait for the
12997 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080012998 final BroadcastQueue queue = broadcastQueueForIntent(intent);
12999 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013000 callerPackage, callingPid, callingUid, requiredPermission,
13001 registeredReceivers, resultTo, resultCode, resultData, map,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013002 ordered, sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013003 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080013004 TAG, "Enqueueing parallel broadcast " + r);
13005 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013006 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013007 queue.enqueueParallelBroadcastLocked(r);
13008 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013010 registeredReceivers = null;
13011 NR = 0;
13012 }
13013
13014 // Merge into one list.
13015 int ir = 0;
13016 if (receivers != null) {
13017 // A special case for PACKAGE_ADDED: do not allow the package
13018 // being added to see this broadcast. This prevents them from
13019 // using this as a back door to get run as soon as they are
13020 // installed. Maybe in the future we want to have a special install
13021 // broadcast or such for apps, but we'd like to deliberately make
13022 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013023 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013024 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
13025 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
13026 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013027 Uri data = intent.getData();
13028 if (data != null) {
13029 String pkgName = data.getSchemeSpecificPart();
13030 if (pkgName != null) {
13031 skipPackages = new String[] { pkgName };
13032 }
13033 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070013034 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013035 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070013036 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080013037 if (skipPackages != null && (skipPackages.length > 0)) {
13038 for (String skipPackage : skipPackages) {
13039 if (skipPackage != null) {
13040 int NT = receivers.size();
13041 for (int it=0; it<NT; it++) {
13042 ResolveInfo curt = (ResolveInfo)receivers.get(it);
13043 if (curt.activityInfo.packageName.equals(skipPackage)) {
13044 receivers.remove(it);
13045 it--;
13046 NT--;
13047 }
13048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013049 }
13050 }
13051 }
13052
13053 int NT = receivers != null ? receivers.size() : 0;
13054 int it = 0;
13055 ResolveInfo curt = null;
13056 BroadcastFilter curr = null;
13057 while (it < NT && ir < NR) {
13058 if (curt == null) {
13059 curt = (ResolveInfo)receivers.get(it);
13060 }
13061 if (curr == null) {
13062 curr = registeredReceivers.get(ir);
13063 }
13064 if (curr.getPriority() >= curt.priority) {
13065 // Insert this broadcast record into the final list.
13066 receivers.add(it, curr);
13067 ir++;
13068 curr = null;
13069 it++;
13070 NT++;
13071 } else {
13072 // Skip to the next ResolveInfo in the final list.
13073 it++;
13074 curt = null;
13075 }
13076 }
13077 }
13078 while (ir < NR) {
13079 if (receivers == null) {
13080 receivers = new ArrayList();
13081 }
13082 receivers.add(registeredReceivers.get(ir));
13083 ir++;
13084 }
13085
13086 if ((receivers != null && receivers.size() > 0)
13087 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013088 BroadcastQueue queue = broadcastQueueForIntent(intent);
13089 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013090 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080013091 receivers, resultTo, resultCode, resultData, map, ordered,
13092 sticky, false);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013093 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013094 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080013095 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013096 if (DEBUG_BROADCAST) {
13097 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013098 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013099 }
Christopher Tatef46723b2012-01-26 14:19:24 -080013100 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013101 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013102 queue.enqueueOrderedBroadcastLocked(r);
13103 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013105 }
13106
Dianne Hackborna4972e92012-03-14 10:38:05 -070013107 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013108 }
13109
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013110 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013111 // Refuse possible leaked file descriptors
13112 if (intent != null && intent.hasFileDescriptors() == true) {
13113 throw new IllegalArgumentException("File descriptors passed in Intent");
13114 }
13115
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013116 int flags = intent.getFlags();
13117
13118 if (!mProcessesReady) {
13119 // if the caller really truly claims to know what they're doing, go
13120 // ahead and allow the broadcast without launching any receivers
13121 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
13122 intent = new Intent(intent);
13123 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
13124 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
13125 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
13126 + " before boot completion");
13127 throw new IllegalStateException("Cannot broadcast before boot completed");
13128 }
13129 }
13130
13131 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
13132 throw new IllegalArgumentException(
13133 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
13134 }
13135
13136 return intent;
13137 }
13138
13139 public final int broadcastIntent(IApplicationThread caller,
13140 Intent intent, String resolvedType, IIntentReceiver resultTo,
13141 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013142 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013143 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013144 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013145 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070013146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013147 final ProcessRecord callerApp = getRecordForAppLocked(caller);
13148 final int callingPid = Binder.getCallingPid();
13149 final int callingUid = Binder.getCallingUid();
13150 final long origId = Binder.clearCallingIdentity();
13151 int res = broadcastIntentLocked(callerApp,
13152 callerApp != null ? callerApp.info.packageName : null,
13153 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070013154 resultCode, resultData, map, requiredPermission, serialized, sticky,
13155 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013156 Binder.restoreCallingIdentity(origId);
13157 return res;
13158 }
13159 }
13160
13161 int broadcastIntentInPackage(String packageName, int uid,
13162 Intent intent, String resolvedType, IIntentReceiver resultTo,
13163 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070013164 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013165 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070013166 intent = verifyBroadcastLocked(intent);
13167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013168 final long origId = Binder.clearCallingIdentity();
13169 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
13170 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070013171 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013172 Binder.restoreCallingIdentity(origId);
13173 return res;
13174 }
13175 }
13176
Amith Yamasani742a6712011-05-04 14:49:28 -070013177 // TODO: Use the userId; maybe mStickyBroadcasts need to be tied to the user.
13178 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013179 // Refuse possible leaked file descriptors
13180 if (intent != null && intent.hasFileDescriptors() == true) {
13181 throw new IllegalArgumentException("File descriptors passed in Intent");
13182 }
13183
13184 synchronized(this) {
13185 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
13186 != PackageManager.PERMISSION_GRANTED) {
13187 String msg = "Permission Denial: unbroadcastIntent() from pid="
13188 + Binder.getCallingPid()
13189 + ", uid=" + Binder.getCallingUid()
13190 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013191 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013192 throw new SecurityException(msg);
13193 }
13194 ArrayList<Intent> list = mStickyBroadcasts.get(intent.getAction());
13195 if (list != null) {
13196 int N = list.size();
13197 int i;
13198 for (i=0; i<N; i++) {
13199 if (intent.filterEquals(list.get(i))) {
13200 list.remove(i);
13201 break;
13202 }
13203 }
13204 }
13205 }
13206 }
13207
13208 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
13209 String resultData, Bundle resultExtras, boolean resultAbort,
13210 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080013211 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
13212 if (r == null) {
13213 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013214 return false;
13215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013216
Christopher Tatef46723b2012-01-26 14:19:24 -080013217 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
13218 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013219 }
13220
13221 public void finishReceiver(IBinder who, int resultCode, String resultData,
13222 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013223 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013224
13225 // Refuse possible leaked file descriptors
13226 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
13227 throw new IllegalArgumentException("File descriptors passed in Bundle");
13228 }
13229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013230 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080013231 try {
13232 boolean doNext = false;
13233 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013234
Christopher Tatef46723b2012-01-26 14:19:24 -080013235 synchronized(this) {
13236 r = broadcastRecordForReceiverLocked(who);
13237 if (r != null) {
13238 doNext = r.queue.finishReceiverLocked(r, resultCode,
13239 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013241 }
Jeff Brown4d94a762010-09-23 11:33:28 -070013242
Christopher Tatef46723b2012-01-26 14:19:24 -080013243 if (doNext) {
13244 r.queue.processNextBroadcast(false);
13245 }
13246 trimApplications();
13247 } finally {
13248 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070013249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013252 // =========================================================
13253 // INSTRUMENTATION
13254 // =========================================================
13255
13256 public boolean startInstrumentation(ComponentName className,
13257 String profileFile, int flags, Bundle arguments,
13258 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013259 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013260 // Refuse possible leaked file descriptors
13261 if (arguments != null && arguments.hasFileDescriptors()) {
13262 throw new IllegalArgumentException("File descriptors passed in Bundle");
13263 }
13264
13265 synchronized(this) {
13266 InstrumentationInfo ii = null;
13267 ApplicationInfo ai = null;
13268 try {
13269 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070013270 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013271 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070013272 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013273 } catch (PackageManager.NameNotFoundException e) {
13274 }
13275 if (ii == null) {
13276 reportStartInstrumentationFailure(watcher, className,
13277 "Unable to find instrumentation info for: " + className);
13278 return false;
13279 }
13280 if (ai == null) {
13281 reportStartInstrumentationFailure(watcher, className,
13282 "Unable to find instrumentation target package: " + ii.targetPackage);
13283 return false;
13284 }
13285
13286 int match = mContext.getPackageManager().checkSignatures(
13287 ii.targetPackage, ii.packageName);
13288 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
13289 String msg = "Permission Denial: starting instrumentation "
13290 + className + " from pid="
13291 + Binder.getCallingPid()
13292 + ", uid=" + Binder.getCallingPid()
13293 + " not allowed because package " + ii.packageName
13294 + " does not have a signature matching the target "
13295 + ii.targetPackage;
13296 reportStartInstrumentationFailure(watcher, className, msg);
13297 throw new SecurityException(msg);
13298 }
13299
Amith Yamasani483f3b02012-03-13 16:08:00 -070013300 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013301 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070013302 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070013303 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013304 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013305 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013306 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013307 app.instrumentationProfileFile = profileFile;
13308 app.instrumentationArguments = arguments;
13309 app.instrumentationWatcher = watcher;
13310 app.instrumentationResultClass = className;
13311 Binder.restoreCallingIdentity(origId);
13312 }
13313
13314 return true;
13315 }
13316
13317 /**
13318 * Report errors that occur while attempting to start Instrumentation. Always writes the
13319 * error to the logs, but if somebody is watching, send the report there too. This enables
13320 * the "am" command to report errors with more information.
13321 *
13322 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
13323 * @param cn The component name of the instrumentation.
13324 * @param report The error report.
13325 */
13326 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
13327 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013328 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013329 try {
13330 if (watcher != null) {
13331 Bundle results = new Bundle();
13332 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
13333 results.putString("Error", report);
13334 watcher.instrumentationStatus(cn, -1, results);
13335 }
13336 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013337 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013338 }
13339 }
13340
13341 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
13342 if (app.instrumentationWatcher != null) {
13343 try {
13344 // NOTE: IInstrumentationWatcher *must* be oneway here
13345 app.instrumentationWatcher.instrumentationFinished(
13346 app.instrumentationClass,
13347 resultCode,
13348 results);
13349 } catch (RemoteException e) {
13350 }
13351 }
13352 app.instrumentationWatcher = null;
13353 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070013354 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013355 app.instrumentationProfileFile = null;
13356 app.instrumentationArguments = null;
13357
Amith Yamasani483f3b02012-03-13 16:08:00 -070013358 forceStopPackageLocked(app.processName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013359 }
13360
13361 public void finishInstrumentation(IApplicationThread target,
13362 int resultCode, Bundle results) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070013363 int userId = UserId.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013364 // Refuse possible leaked file descriptors
13365 if (results != null && results.hasFileDescriptors()) {
13366 throw new IllegalArgumentException("File descriptors passed in Intent");
13367 }
13368
13369 synchronized(this) {
13370 ProcessRecord app = getRecordForAppLocked(target);
13371 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013372 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013373 return;
13374 }
13375 final long origId = Binder.clearCallingIdentity();
13376 finishInstrumentationLocked(app, resultCode, results);
13377 Binder.restoreCallingIdentity(origId);
13378 }
13379 }
13380
13381 // =========================================================
13382 // CONFIGURATION
13383 // =========================================================
13384
13385 public ConfigurationInfo getDeviceConfigurationInfo() {
13386 ConfigurationInfo config = new ConfigurationInfo();
13387 synchronized (this) {
13388 config.reqTouchScreen = mConfiguration.touchscreen;
13389 config.reqKeyboardType = mConfiguration.keyboard;
13390 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013391 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
13392 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013393 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
13394 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070013395 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
13396 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013397 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
13398 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070013399 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013400 }
13401 return config;
13402 }
13403
13404 public Configuration getConfiguration() {
13405 Configuration ci;
13406 synchronized(this) {
13407 ci = new Configuration(mConfiguration);
13408 }
13409 return ci;
13410 }
13411
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013412 public void updatePersistentConfiguration(Configuration values) {
13413 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13414 "updateConfiguration()");
13415 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
13416 "updateConfiguration()");
13417 if (values == null) {
13418 throw new NullPointerException("Configuration must not be null");
13419 }
13420
13421 synchronized(this) {
13422 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080013423 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013424 Binder.restoreCallingIdentity(origId);
13425 }
13426 }
13427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013428 public void updateConfiguration(Configuration values) {
13429 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
13430 "updateConfiguration()");
13431
13432 synchronized(this) {
13433 if (values == null && mWindowManager != null) {
13434 // sentinel: fetch the current configuration from the window manager
13435 values = mWindowManager.computeNewConfiguration();
13436 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013437
13438 if (mWindowManager != null) {
13439 mProcessList.applyDisplaySize(mWindowManager);
13440 }
13441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013442 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013443 if (values != null) {
13444 Settings.System.clearConfiguration(values);
13445 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080013446 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013447 Binder.restoreCallingIdentity(origId);
13448 }
13449 }
13450
13451 /**
13452 * Do either or both things: (1) change the current configuration, and (2)
13453 * make sure the given activity is running with the (now) current
13454 * configuration. Returns true if the activity has been left running, or
13455 * false if <var>starting</var> is being destroyed to match the new
13456 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013457 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013458 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013459 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080013460 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070013461 // do nothing if we are headless
13462 if (mHeadless) return true;
13463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013464 int changes = 0;
13465
13466 boolean kept = true;
13467
13468 if (values != null) {
13469 Configuration newConfig = new Configuration(mConfiguration);
13470 changes = newConfig.updateFrom(values);
13471 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013472 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013473 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013474 }
13475
Doug Zongker2bec3d42009-12-04 12:52:44 -080013476 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013477
Dianne Hackborn813075a62011-11-14 17:45:19 -080013478 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013479 saveLocaleLocked(values.locale,
13480 !values.locale.equals(mConfiguration.locale),
13481 values.userSetLocale);
13482 }
13483
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013484 mConfigurationSeq++;
13485 if (mConfigurationSeq <= 0) {
13486 mConfigurationSeq = 1;
13487 }
13488 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013489 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080013490 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013491
13492 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070013493
13494 // TODO: If our config changes, should we auto dismiss any currently
13495 // showing dialogs?
13496 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013497
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013498 AttributeCache ac = AttributeCache.instance();
13499 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080013500 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080013501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013502
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013503 // Make sure all resources in our process are updated
13504 // right now, so that anyone who is going to retrieve
13505 // resource values after we return will be sure to get
13506 // the new ones. This is especially important during
13507 // boot, where the first config change needs to guarantee
13508 // all resources have that config before following boot
13509 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080013510 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070013511
Dianne Hackborn31ca8542011-07-19 14:58:28 -070013512 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013513 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013514 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080013515 mHandler.sendMessage(msg);
13516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013517
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013518 for (int i=mLruProcesses.size()-1; i>=0; i--) {
13519 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013520 try {
13521 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013522 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070013523 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080013524 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013525 }
13526 } catch (Exception e) {
13527 }
13528 }
13529 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080013530 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
13531 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013532 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013533 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013534 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
13535 broadcastIntentLocked(null, null,
13536 new Intent(Intent.ACTION_LOCALE_CHANGED),
13537 null, null, 0, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -070013538 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080013539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013540 }
13541 }
13542
13543 if (changes != 0 && starting == null) {
13544 // If the configuration changed, and the caller is not already
13545 // in the process of starting an activity, then find the top
13546 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013547 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013548 }
13549
13550 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013551 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080013552 // And we need to make sure at this point that all other activities
13553 // are made visible with the correct configuration.
13554 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013555 }
13556
Dianne Hackborne36d6e22010-02-17 19:46:25 -080013557 if (values != null && mWindowManager != null) {
13558 mWindowManager.setNewConfiguration(mConfiguration);
13559 }
13560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013561 return kept;
13562 }
Joe Onorato54a4a412011-11-02 20:50:08 -070013563
13564 /**
13565 * Decide based on the configuration whether we should shouw the ANR,
13566 * crash, etc dialogs. The idea is that if there is no affordnace to
13567 * press the on-screen buttons, we shouldn't show the dialog.
13568 *
13569 * A thought: SystemUI might also want to get told about this, the Power
13570 * dialog / global actions also might want different behaviors.
13571 */
13572 private static final boolean shouldShowDialogs(Configuration config) {
13573 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
13574 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
13575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013576
13577 /**
13578 * Save the locale. You must be inside a synchronized (this) block.
13579 */
13580 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
13581 if(isDiff) {
13582 SystemProperties.set("user.language", l.getLanguage());
13583 SystemProperties.set("user.region", l.getCountry());
13584 }
13585
13586 if(isPersist) {
13587 SystemProperties.set("persist.sys.language", l.getLanguage());
13588 SystemProperties.set("persist.sys.country", l.getCountry());
13589 SystemProperties.set("persist.sys.localevar", l.getVariant());
13590 }
13591 }
13592
Adam Powelldd8fab22012-03-22 17:47:27 -070013593 @Override
13594 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
13595 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013596 return srec != null && srec.task.affinity != null &&
13597 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070013598 }
13599
13600 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
13601 Intent resultData) {
13602 ComponentName dest = destIntent.getComponent();
13603
13604 synchronized (this) {
13605 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070013606 if (srec == null) {
13607 return false;
13608 }
Adam Powelldd8fab22012-03-22 17:47:27 -070013609 ArrayList<ActivityRecord> history = srec.stack.mHistory;
13610 final int start = history.indexOf(srec);
13611 if (start < 0) {
13612 // Current activity is not in history stack; do nothing.
13613 return false;
13614 }
13615 int finishTo = start - 1;
13616 ActivityRecord parent = null;
13617 boolean foundParentInTask = false;
13618 if (dest != null) {
13619 TaskRecord tr = srec.task;
13620 for (int i = start - 1; i >= 0; i--) {
13621 ActivityRecord r = history.get(i);
13622 if (tr != r.task) {
13623 // Couldn't find parent in the same task; stop at the one above this.
13624 // (Root of current task; in-app "home" behavior)
13625 // Always at least finish the current activity.
13626 finishTo = Math.min(start - 1, i + 1);
13627 parent = history.get(finishTo);
13628 break;
13629 } else if (r.info.packageName.equals(dest.getPackageName()) &&
13630 r.info.name.equals(dest.getClassName())) {
13631 finishTo = i;
13632 parent = r;
13633 foundParentInTask = true;
13634 break;
13635 }
13636 }
13637 }
13638
13639 if (mController != null) {
13640 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
13641 if (next != null) {
13642 // ask watcher if this is allowed
13643 boolean resumeOK = true;
13644 try {
13645 resumeOK = mController.activityResuming(next.packageName);
13646 } catch (RemoteException e) {
13647 mController = null;
13648 }
13649
13650 if (!resumeOK) {
13651 return false;
13652 }
13653 }
13654 }
13655 final long origId = Binder.clearCallingIdentity();
13656 for (int i = start; i > finishTo; i--) {
13657 ActivityRecord r = history.get(i);
13658 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
13659 "navigate-up");
13660 // Only return the supplied result for the first activity finished
13661 resultCode = Activity.RESULT_CANCELED;
13662 resultData = null;
13663 }
13664
13665 if (parent != null && foundParentInTask) {
13666 final int parentLaunchMode = parent.info.launchMode;
13667 final int destIntentFlags = destIntent.getFlags();
13668 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
13669 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
13670 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
13671 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070013672 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070013673 } else {
13674 try {
13675 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
13676 destIntent.getComponent(), 0, UserId.getCallingUserId());
13677 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
13678 null, aInfo, parent.appToken, null,
13679 0, -1, parent.launchedFromUid, 0, null, true, null);
13680 foundParentInTask = res == ActivityManager.START_SUCCESS;
13681 } catch (RemoteException e) {
13682 foundParentInTask = false;
13683 }
13684 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
13685 resultData, "navigate-up");
13686 }
13687 }
13688 Binder.restoreCallingIdentity(origId);
13689 return foundParentInTask;
13690 }
13691 }
13692
Dianne Hackborn5320eb82012-05-18 12:05:04 -070013693 public int getLaunchedFromUid(IBinder activityToken) {
13694 ActivityRecord srec = ActivityRecord.forToken(activityToken);
13695 if (srec == null) {
13696 return -1;
13697 }
13698 return srec.launchedFromUid;
13699 }
13700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013701 // =========================================================
13702 // LIFETIME MANAGEMENT
13703 // =========================================================
13704
Christopher Tatef46723b2012-01-26 14:19:24 -080013705 // Returns which broadcast queue the app is the current [or imminent] receiver
13706 // on, or 'null' if the app is not an active broadcast recipient.
13707 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
13708 BroadcastRecord r = app.curReceiver;
13709 if (r != null) {
13710 return r.queue;
13711 }
13712
13713 // It's not the current receiver, but it might be starting up to become one
13714 synchronized (this) {
13715 for (BroadcastQueue queue : mBroadcastQueues) {
13716 r = queue.mPendingBroadcast;
13717 if (r != null && r.curApp == app) {
13718 // found it; report which queue it's in
13719 return queue;
13720 }
13721 }
13722 }
13723
13724 return null;
13725 }
13726
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013727 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013728 ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013729 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013730 // This adjustment has already been computed. If we are calling
13731 // from the top, we may have already computed our adjustment with
13732 // an earlier hidden adjustment that isn't really for us... if
13733 // so, use the new hidden adjustment.
13734 if (!recursed && app.hidden) {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013735 app.curAdj = app.curRawAdj = app.nonStoppingAdj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013736 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013737 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013738 }
13739
13740 if (app.thread == null) {
13741 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013742 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013743 return (app.curAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013744 }
13745
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013746 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
13747 app.adjSource = null;
13748 app.adjTarget = null;
13749 app.empty = false;
13750 app.hidden = false;
13751
13752 final int activitiesSize = app.activities.size();
13753
Dianne Hackborn7d608422011-08-07 16:24:18 -070013754 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013755 // The max adjustment doesn't allow this app to be anything
13756 // below foreground, so it is not worth doing work for it.
13757 app.adjType = "fixed";
13758 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013759 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013760 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013761 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013762 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013763 // System process can do UI, and when they do we want to have
13764 // them trim their memory after the user leaves the UI. To
13765 // facilitate this, here we need to determine whether or not it
13766 // is currently showing UI.
13767 app.systemNoUi = true;
13768 if (app == TOP_APP) {
13769 app.systemNoUi = false;
13770 } else if (activitiesSize > 0) {
13771 for (int j = 0; j < activitiesSize; j++) {
13772 final ActivityRecord r = app.activities.get(j);
13773 if (r.visible) {
13774 app.systemNoUi = false;
13775 break;
13776 }
13777 }
13778 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013779 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013780 }
13781
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013782 app.keeping = false;
13783 app.systemNoUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013784
The Android Open Source Project4df24232009-03-05 14:34:35 -080013785 // Determine the importance of the process, starting with most
13786 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013787 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013788 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013789 boolean foregroundActivities = false;
13790 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080013791 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013792 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013793 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013794 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013795 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013796 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013797 foregroundActivities = true;
13798 interesting = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013799 } else if (app.instrumentationClass != null) {
13800 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013801 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013802 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013803 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013804 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080013805 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013806 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080013807 // counts as being in the foreground for OOM killer purposes.
13808 // It's placed in a sched group based on the nature of the
13809 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013810 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080013811 schedGroup = (queue == mFgBroadcastQueue)
13812 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013813 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013814 } else if (app.executingServices.size() > 0) {
13815 // An app that is currently executing a service callback also
13816 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013817 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013818 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013819 app.adjType = "exec-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013820 } else if (activitiesSize > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013821 // This app is in the background with paused activities.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013822 // We inspect activities to potentially upgrade adjustment further below.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013823 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013824 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013825 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013826 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013827 } else {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013828 // A very not-needed process. If this is lower in the lru list,
13829 // we will push it in to the empty bucket.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013830 adj = hiddenAdj;
13831 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013832 app.hidden = true;
13833 app.empty = true;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013834 app.adjType = "bg-empty";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013835 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013836
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013837 boolean hasStoppingActivities = false;
13838
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013839 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013840 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013841 for (int j = 0; j < activitiesSize; j++) {
13842 final ActivityRecord r = app.activities.get(j);
13843 if (r.visible) {
13844 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013845 if (adj > ProcessList.VISIBLE_APP_ADJ) {
13846 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013847 app.adjType = "visible";
13848 }
13849 schedGroup = Process.THREAD_GROUP_DEFAULT;
13850 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013851 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013852 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013853 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013854 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
13855 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013856 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013857 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080013858 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013859 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013860 } else if (r.state == ActivityState.STOPPING) {
13861 // We will apply the actual adjustment later, because
13862 // we want to allow this process to immediately go through
13863 // any memory trimming that is in effect.
13864 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013865 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013866 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013867 }
13868 }
13869 }
13870
Dianne Hackborn7d608422011-08-07 16:24:18 -070013871 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013872 if (app.foregroundServices) {
13873 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013874 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013875 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013876 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013877 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013878 } else if (app.forcingToForeground != null) {
13879 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013880 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013881 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013882 app.adjType = "force-foreground";
13883 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013884 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013885 }
13886 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070013887
Dianne Hackborna93c2c12012-05-31 15:29:36 -070013888 if (app.foregroundServices) {
13889 interesting = true;
13890 }
13891
Dianne Hackborn7d608422011-08-07 16:24:18 -070013892 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013893 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013894 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013895 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013896 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013897 app.adjType = "heavy";
13898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013899
Dianne Hackborn7d608422011-08-07 16:24:18 -070013900 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013901 // This process is hosting what we currently consider to be the
13902 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070013903 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013904 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013905 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080013906 app.adjType = "home";
13907 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013908
Dianne Hackbornf35fe232011-11-01 19:25:20 -070013909 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
13910 && app.activities.size() > 0) {
13911 // This was the previous process that showed UI to the user.
13912 // We want to try to keep it around more aggressively, to give
13913 // a good experience around switching between two apps.
13914 adj = ProcessList.PREVIOUS_APP_ADJ;
13915 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
13916 app.hidden = false;
13917 app.adjType = "previous";
13918 }
13919
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013920 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
13921 + " reason=" + app.adjType);
13922
The Android Open Source Project4df24232009-03-05 14:34:35 -080013923 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013924 // there are applications dependent on our services or providers, but
13925 // this gives us a baseline and makes sure we don't get into an
13926 // infinite recursion.
13927 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013928 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013929
Christopher Tate6fa95972009-06-05 18:43:55 -070013930 if (mBackupTarget != null && app == mBackupTarget.app) {
13931 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070013932 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013933 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013934 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070013935 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013936 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070013937 }
13938 }
13939
Dianne Hackborn7d608422011-08-07 16:24:18 -070013940 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013941 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013942 final long now = SystemClock.uptimeMillis();
13943 // This process is more important if the top activity is
13944 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070013945 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013946 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070013947 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013948 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070013949 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013950 // If this process has shown some UI, let it immediately
13951 // go to the LRU list because it may be pretty heavy with
13952 // UI stuff. We'll tag it with a label just to help
13953 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013954 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013955 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013956 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013957 } else {
13958 if (now < (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
13959 // This service has seen some activity within
13960 // recent memory, so we will keep its process ahead
13961 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013962 if (adj > ProcessList.SERVICE_ADJ) {
13963 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013964 app.adjType = "started-services";
13965 app.hidden = false;
13966 }
13967 }
13968 // If we have let the service slide into the background
13969 // state, still have some text describing what it is doing
13970 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013971 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070013972 app.adjType = "started-bg-services";
13973 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013974 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013975 // Don't kill this process because it is doing work; it
13976 // has said it is doing work.
13977 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013978 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070013979 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080013980 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013981 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013982 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013983 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013984 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013985 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013986 // XXX should compute this based on the max of
13987 // all connected clients.
13988 ConnectionRecord cr = clist.get(i);
13989 if (cr.binding.client == app) {
13990 // Binding to ourself is not interesting.
13991 continue;
13992 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013993 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013994 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013995 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013996 int myHiddenAdj = hiddenAdj;
13997 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070013998 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070013999 myHiddenAdj = client.hiddenAdj;
14000 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014001 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014002 }
14003 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014004 clientAdj = computeOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014005 client, myHiddenAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014006 String adjType = null;
14007 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
14008 // Not doing bind OOM management, so treat
14009 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014010 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014011 // If this process has shown some UI, let it immediately
14012 // go to the LRU list because it may be pretty heavy with
14013 // UI stuff. We'll tag it with a label just to help
14014 // debug and understand what is going on.
14015 if (adj > clientAdj) {
14016 adjType = "bound-bg-ui-services";
14017 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014018 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014019 clientAdj = adj;
14020 } else {
14021 if (now >= (s.lastActivity+MAX_SERVICE_INACTIVITY)) {
14022 // This service has not seen activity within
14023 // recent memory, so allow it to drop to the
14024 // LRU list if there is no other reason to keep
14025 // it around. We'll also tag it with a label just
14026 // to help debug and undertand what is going on.
14027 if (adj > clientAdj) {
14028 adjType = "bound-bg-services";
14029 }
14030 clientAdj = adj;
14031 }
14032 }
14033 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014034 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014035 // If this process has recently shown UI, and
14036 // the process that is binding to it is less
14037 // important than being visible, then we don't
14038 // care about the binding as much as we care
14039 // about letting this process get into the LRU
14040 // list to be killed and restarted if needed for
14041 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070014042 if (app.hasShownUi && app != mHomeProcess
14043 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014044 adjType = "bound-bg-ui-services";
14045 } else {
14046 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
14047 |Context.BIND_IMPORTANT)) != 0) {
14048 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014049 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
14050 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
14051 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14052 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14053 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014054 adj = clientAdj;
14055 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070014056 app.pendingUiClean = true;
14057 if (adj > ProcessList.VISIBLE_APP_ADJ) {
14058 adj = ProcessList.VISIBLE_APP_ADJ;
14059 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014060 }
14061 if (!client.hidden) {
14062 app.hidden = false;
14063 }
14064 if (client.keeping) {
14065 app.keeping = true;
14066 }
14067 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014068 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014069 }
14070 if (adjType != null) {
14071 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014072 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14073 .REASON_SERVICE_IN_USE;
14074 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014075 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070014076 app.adjTarget = s.name;
14077 }
14078 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14079 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14080 schedGroup = Process.THREAD_GROUP_DEFAULT;
14081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014082 }
14083 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014084 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
14085 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014086 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014087 (a.visible || a.state == ActivityState.RESUMED
14088 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014089 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014090 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
14091 schedGroup = Process.THREAD_GROUP_DEFAULT;
14092 }
14093 app.hidden = false;
14094 app.adjType = "service";
14095 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14096 .REASON_SERVICE_IN_USE;
14097 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070014098 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014099 app.adjTarget = s.name;
14100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014102 }
14103 }
14104 }
14105 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014106
Dianne Hackborn287952c2010-09-22 22:34:31 -070014107 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014108 // would like to avoid killing it unless it would prevent the current
14109 // application from running. By default we put the process in
14110 // with the rest of the background processes; as we scan through
14111 // its services we may bump it up from there.
14112 if (adj > hiddenAdj) {
14113 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014114 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070014115 app.adjType = "bg-services";
14116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014117 }
14118
Dianne Hackborn7d608422011-08-07 16:24:18 -070014119 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014120 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014121 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014122 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014123 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070014124 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014125 for (int i = cpr.connections.size()-1;
14126 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
14127 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
14128 i--) {
14129 ContentProviderConnection conn = cpr.connections.get(i);
14130 ProcessRecord client = conn.client;
14131 if (client == app) {
14132 // Being our own client is not interesting.
14133 continue;
14134 }
14135 int myHiddenAdj = hiddenAdj;
14136 if (myHiddenAdj > client.hiddenAdj) {
14137 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
14138 myHiddenAdj = client.hiddenAdj;
14139 } else {
14140 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070014141 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014142 }
14143 int clientAdj = computeOomAdjLocked(
14144 client, myHiddenAdj, TOP_APP, true, doingAll);
14145 if (adj > clientAdj) {
14146 if (app.hasShownUi && app != mHomeProcess
14147 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14148 app.adjType = "bg-ui-provider";
14149 } else {
14150 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
14151 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
14152 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014153 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014154 if (!client.hidden) {
14155 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014156 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014157 if (client.keeping) {
14158 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014159 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070014160 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
14161 .REASON_PROVIDER_IN_USE;
14162 app.adjSource = client;
14163 app.adjSourceOom = clientAdj;
14164 app.adjTarget = cpr.name;
14165 }
14166 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
14167 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014168 }
14169 }
14170 // If the provider has external (non-framework) process
14171 // dependencies, ensure that its adjustment is at least
14172 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080014173 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014174 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
14175 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014176 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014177 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014178 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070014179 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070014180 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014181 }
14182 }
14183 }
14184 }
14185
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014186 if (adj == ProcessList.SERVICE_ADJ) {
14187 if (doingAll) {
14188 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
14189 mNewNumServiceProcs++;
14190 }
14191 if (app.serviceb) {
14192 adj = ProcessList.SERVICE_B_ADJ;
14193 }
14194 } else {
14195 app.serviceb = false;
14196 }
14197
14198 app.nonStoppingAdj = adj;
14199
14200 if (hasStoppingActivities) {
14201 // Only upgrade adjustment.
14202 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
14203 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14204 app.adjType = "stopping";
14205 }
14206 }
14207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014208 app.curRawAdj = adj;
14209
Joe Onorato8a9b2202010-02-26 18:56:32 -080014210 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014211 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
14212 if (adj > app.maxAdj) {
14213 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014214 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080014215 schedGroup = Process.THREAD_GROUP_DEFAULT;
14216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014217 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070014218 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014219 app.keeping = true;
14220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014221
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014222 if (app.hasAboveClient) {
14223 // If this process has bound to any services with BIND_ABOVE_CLIENT,
14224 // then we need to drop its adjustment to be lower than the service's
14225 // in order to honor the request. We want to drop it by one adjustment
14226 // level... but there is special meaning applied to various levels so
14227 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014228 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014229 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070014230 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
14231 adj = ProcessList.VISIBLE_APP_ADJ;
14232 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
14233 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
14234 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
14235 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014236 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014237 adj++;
14238 }
14239 }
14240
Dianne Hackborna93c2c12012-05-31 15:29:36 -070014241 int importance = app.memImportance;
14242 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
14243 app.curAdj = adj;
14244 app.curSchedGroup = schedGroup;
14245 if (!interesting) {
14246 // For this reporting, if there is not something explicitly
14247 // interesting in this process then we will push it to the
14248 // background importance.
14249 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
14250 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
14251 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
14252 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
14253 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
14254 } else if (adj >= ProcessList.HOME_APP_ADJ) {
14255 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
14256 } else if (adj >= ProcessList.SERVICE_ADJ) {
14257 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
14258 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
14259 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
14260 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
14261 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
14262 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
14263 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
14264 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
14265 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
14266 } else {
14267 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
14268 }
14269 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014270
Dianne Hackborna93c2c12012-05-31 15:29:36 -070014271 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
14272 if (foregroundActivities != app.foregroundActivities) {
14273 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
14274 }
14275 if (changes != 0) {
14276 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
14277 app.memImportance = importance;
14278 app.foregroundActivities = foregroundActivities;
14279 int i = mPendingProcessChanges.size()-1;
14280 ProcessChangeItem item = null;
14281 while (i >= 0) {
14282 item = mPendingProcessChanges.get(i);
14283 if (item.pid == app.pid) {
14284 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
14285 break;
14286 }
14287 i--;
14288 }
14289 if (i < 0) {
14290 // No existing item in pending changes; need a new one.
14291 final int NA = mAvailProcessChanges.size();
14292 if (NA > 0) {
14293 item = mAvailProcessChanges.remove(NA-1);
14294 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
14295 } else {
14296 item = new ProcessChangeItem();
14297 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
14298 }
14299 item.changes = 0;
14300 item.pid = app.pid;
14301 item.uid = app.info.uid;
14302 if (mPendingProcessChanges.size() == 0) {
14303 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
14304 "*** Enqueueing dispatch processes changed!");
14305 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
14306 }
14307 mPendingProcessChanges.add(item);
14308 }
14309 item.changes |= changes;
14310 item.importance = importance;
14311 item.foregroundActivities = foregroundActivities;
14312 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
14313 + Integer.toHexString(System.identityHashCode(item))
14314 + " " + app.toShortString() + ": changes=" + item.changes
14315 + " importance=" + item.importance
14316 + " foreground=" + item.foregroundActivities
14317 + " type=" + app.adjType + " source=" + app.adjSource
14318 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070014319 }
14320
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014321 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014322 }
14323
14324 /**
14325 * Ask a given process to GC right now.
14326 */
14327 final void performAppGcLocked(ProcessRecord app) {
14328 try {
14329 app.lastRequestedGc = SystemClock.uptimeMillis();
14330 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014331 if (app.reportLowMemory) {
14332 app.reportLowMemory = false;
14333 app.thread.scheduleLowMemory();
14334 } else {
14335 app.thread.processInBackground();
14336 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014337 }
14338 } catch (Exception e) {
14339 // whatever.
14340 }
14341 }
14342
14343 /**
14344 * Returns true if things are idle enough to perform GCs.
14345 */
Josh Bartel7f208742010-02-25 11:01:44 -060014346 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080014347 boolean processingBroadcasts = false;
14348 for (BroadcastQueue q : mBroadcastQueues) {
14349 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
14350 processingBroadcasts = true;
14351 }
14352 }
14353 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014354 && (mSleeping || (mMainStack.mResumedActivity != null &&
14355 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014356 }
14357
14358 /**
14359 * Perform GCs on all processes that are waiting for it, but only
14360 * if things are idle.
14361 */
14362 final void performAppGcsLocked() {
14363 final int N = mProcessesToGc.size();
14364 if (N <= 0) {
14365 return;
14366 }
Josh Bartel7f208742010-02-25 11:01:44 -060014367 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014368 while (mProcessesToGc.size() > 0) {
14369 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014370 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014371 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
14372 <= SystemClock.uptimeMillis()) {
14373 // To avoid spamming the system, we will GC processes one
14374 // at a time, waiting a few seconds between each.
14375 performAppGcLocked(proc);
14376 scheduleAppGcsLocked();
14377 return;
14378 } else {
14379 // It hasn't been long enough since we last GCed this
14380 // process... put it in the list to wait for its time.
14381 addProcessToGcListLocked(proc);
14382 break;
14383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014384 }
14385 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014386
14387 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014388 }
14389 }
14390
14391 /**
14392 * If all looks good, perform GCs on all processes waiting for them.
14393 */
14394 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060014395 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014396 performAppGcsLocked();
14397 return;
14398 }
14399 // Still not idle, wait some more.
14400 scheduleAppGcsLocked();
14401 }
14402
14403 /**
14404 * Schedule the execution of all pending app GCs.
14405 */
14406 final void scheduleAppGcsLocked() {
14407 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014408
14409 if (mProcessesToGc.size() > 0) {
14410 // Schedule a GC for the time to the next process.
14411 ProcessRecord proc = mProcessesToGc.get(0);
14412 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
14413
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014414 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014415 long now = SystemClock.uptimeMillis();
14416 if (when < (now+GC_TIMEOUT)) {
14417 when = now + GC_TIMEOUT;
14418 }
14419 mHandler.sendMessageAtTime(msg, when);
14420 }
14421 }
14422
14423 /**
14424 * Add a process to the array of processes waiting to be GCed. Keeps the
14425 * list in sorted order by the last GC time. The process can't already be
14426 * on the list.
14427 */
14428 final void addProcessToGcListLocked(ProcessRecord proc) {
14429 boolean added = false;
14430 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
14431 if (mProcessesToGc.get(i).lastRequestedGc <
14432 proc.lastRequestedGc) {
14433 added = true;
14434 mProcessesToGc.add(i+1, proc);
14435 break;
14436 }
14437 }
14438 if (!added) {
14439 mProcessesToGc.add(0, proc);
14440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014441 }
14442
14443 /**
14444 * Set up to ask a process to GC itself. This will either do it
14445 * immediately, or put it on the list of processes to gc the next
14446 * time things are idle.
14447 */
14448 final void scheduleAppGcLocked(ProcessRecord app) {
14449 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014450 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014451 return;
14452 }
14453 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070014454 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014455 scheduleAppGcsLocked();
14456 }
14457 }
14458
Dianne Hackborn287952c2010-09-22 22:34:31 -070014459 final void checkExcessivePowerUsageLocked(boolean doKills) {
14460 updateCpuStatsNow();
14461
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014462 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014463 boolean doWakeKills = doKills;
14464 boolean doCpuKills = doKills;
14465 if (mLastPowerCheckRealtime == 0) {
14466 doWakeKills = false;
14467 }
14468 if (mLastPowerCheckUptime == 0) {
14469 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014470 }
14471 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070014472 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014473 }
14474 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070014475 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
14476 final long curUptime = SystemClock.uptimeMillis();
14477 final long uptimeSince = curUptime - mLastPowerCheckUptime;
14478 mLastPowerCheckRealtime = curRealtime;
14479 mLastPowerCheckUptime = curUptime;
14480 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
14481 doWakeKills = false;
14482 }
14483 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
14484 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014485 }
14486 int i = mLruProcesses.size();
14487 while (i > 0) {
14488 i--;
14489 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014490 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014491 long wtime;
14492 synchronized (stats) {
14493 wtime = stats.getProcessWakeTime(app.info.uid,
14494 app.pid, curRealtime);
14495 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070014496 long wtimeUsed = wtime - app.lastWakeTime;
14497 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
14498 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014499 StringBuilder sb = new StringBuilder(128);
14500 sb.append("Wake for ");
14501 app.toShortString(sb);
14502 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014503 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014504 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014505 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014506 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070014507 sb.append((wtimeUsed*100)/realtimeSince);
14508 sb.append("%)");
14509 Slog.i(TAG, sb.toString());
14510 sb.setLength(0);
14511 sb.append("CPU for ");
14512 app.toShortString(sb);
14513 sb.append(": over ");
14514 TimeUtils.formatDuration(uptimeSince, sb);
14515 sb.append(" used ");
14516 TimeUtils.formatDuration(cputimeUsed, sb);
14517 sb.append(" (");
14518 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070014519 sb.append("%)");
14520 Slog.i(TAG, sb.toString());
14521 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014522 // If a process has held a wake lock for more
14523 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014524 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070014525 if (doWakeKills && realtimeSince > 0
14526 && ((wtimeUsed*100)/realtimeSince) >= 50) {
14527 synchronized (stats) {
14528 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
14529 realtimeSince, wtimeUsed);
14530 }
14531 Slog.w(TAG, "Excessive wake lock in " + app.processName
14532 + " (pid " + app.pid + "): held " + wtimeUsed
14533 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014534 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14535 app.processName, app.setAdj, "excessive wake lock");
14536 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070014537 } else if (doCpuKills && uptimeSince > 0
14538 && ((cputimeUsed*100)/uptimeSince) >= 50) {
14539 synchronized (stats) {
14540 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
14541 uptimeSince, cputimeUsed);
14542 }
14543 Slog.w(TAG, "Excessive CPU in " + app.processName
14544 + " (pid " + app.pid + "): used " + cputimeUsed
14545 + " during " + uptimeSince);
14546 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14547 app.processName, app.setAdj, "excessive cpu");
14548 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014549 } else {
14550 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070014551 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014552 }
14553 }
14554 }
14555 }
14556
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014557 private final boolean updateOomAdjLocked(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014558 ProcessRecord app, int hiddenAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014559 app.hiddenAdj = hiddenAdj;
14560
14561 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014562 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014563 }
14564
Dianne Hackborn287952c2010-09-22 22:34:31 -070014565 final boolean wasKeeping = app.keeping;
14566
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014567 boolean success = true;
14568
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014569 computeOomAdjLocked(app, hiddenAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014570
Jeff Brown10e89712011-07-08 18:52:57 -070014571 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070014572 if (wasKeeping && !app.keeping) {
14573 // This app is no longer something we want to keep. Note
14574 // its current wake lock time to later know to kill it if
14575 // it is not behaving well.
14576 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
14577 synchronized (stats) {
14578 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
14579 app.pid, SystemClock.elapsedRealtime());
14580 }
14581 app.lastCpuTime = app.curCpuTime;
14582 }
14583
14584 app.setRawAdj = app.curRawAdj;
14585 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014586
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014587 if (app.curAdj != app.setAdj) {
14588 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080014589 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014590 TAG, "Set " + app.pid + " " + app.processName +
14591 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014592 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070014593 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014594 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014595 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070014596 }
14597 }
14598 if (app.setSchedGroup != app.curSchedGroup) {
14599 app.setSchedGroup = app.curSchedGroup;
14600 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
14601 "Setting process group of " + app.processName
14602 + " to " + app.curSchedGroup);
14603 if (app.waitingToKill != null &&
14604 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
14605 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
14606 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14607 app.processName, app.setAdj, app.waitingToKill);
14608 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014609 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070014610 } else {
14611 if (true) {
14612 long oldId = Binder.clearCallingIdentity();
14613 try {
14614 Process.setProcessGroup(app.pid, app.curSchedGroup);
14615 } catch (Exception e) {
14616 Slog.w(TAG, "Failed setting process group of " + app.pid
14617 + " to " + app.curSchedGroup);
14618 e.printStackTrace();
14619 } finally {
14620 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070014621 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014622 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070014623 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014624 try {
Jeff Brown10e89712011-07-08 18:52:57 -070014625 app.thread.setSchedulingGroup(app.curSchedGroup);
14626 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070014627 }
14628 }
14629 }
14630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014631 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014632 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014633 }
14634
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014635 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014636 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014637 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080014638 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014639 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014640 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014641 }
14642 }
14643 return resumedActivity;
14644 }
14645
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014646 private final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014647 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014648 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14649 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070014650 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14651 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014652
14653 mAdjSeq++;
14654
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014655 boolean success = updateOomAdjLocked(app, app.hiddenAdj, TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070014656 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
14657 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014658 if (nowHidden != wasHidden) {
14659 // Changed to/from hidden state, so apps after it in the LRU
14660 // list may also be changed.
14661 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014662 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070014663 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014664 }
14665
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014666 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070014667 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014668 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
14669
14670 if (false) {
14671 RuntimeException e = new RuntimeException();
14672 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080014673 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014674 }
14675
14676 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014677 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014678
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014679 // Let's determine how many processes we have running vs.
14680 // how many slots we have for background processes; we may want
14681 // to put multiple processes in a slot of there are enough of
14682 // them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014683 int numSlots = ProcessList.HIDDEN_APP_MAX_ADJ - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014684 int factor = (mLruProcesses.size()-4)/numSlots;
14685 if (factor < 1) factor = 1;
14686 int step = 0;
Dianne Hackborn8633e682010-04-22 16:03:41 -070014687 int numHidden = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014688 int numTrimming = 0;
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080014689
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014690 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014691 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014692 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070014693 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014694 while (i > 0) {
14695 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014696 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080014697 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014698 updateOomAdjLocked(app, curHiddenAdj, TOP_APP, true);
14699 if (curHiddenAdj < ProcessList.HIDDEN_APP_MAX_ADJ
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014700 && app.curAdj == curHiddenAdj) {
14701 step++;
14702 if (step >= factor) {
14703 step = 0;
14704 curHiddenAdj++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014705 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014706 }
14707 if (!app.killedBackground) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070014708 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014709 numHidden++;
14710 if (numHidden > mProcessLimit) {
14711 Slog.i(TAG, "No longer want " + app.processName
14712 + " (pid " + app.pid + "): hidden #" + numHidden);
14713 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14714 app.processName, app.setAdj, "too many background");
14715 app.killedBackground = true;
14716 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070014717 }
14718 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014719 if (!app.killedBackground && app.isolated && app.services.size() <= 0) {
14720 // If this is an isolated process, and there are no
14721 // services running in it, then the process is no longer
14722 // needed. We agressively kill these because we can by
14723 // definition not re-use the same process again, and it is
14724 // good to avoid having whatever code was running in them
14725 // left sitting around after no longer needed.
14726 Slog.i(TAG, "Isolated process " + app.processName
14727 + " (pid " + app.pid + ") no longer needed");
14728 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14729 app.processName, app.setAdj, "isolated not needed");
14730 app.killedBackground = true;
14731 Process.killProcessQuiet(app.pid);
14732 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014733 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14734 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
14735 && !app.killedBackground) {
14736 numTrimming++;
14737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014738 }
14739 }
14740
Dianne Hackborne02c88a2011-10-28 13:58:15 -070014741 mNumServiceProcs = mNewNumServiceProcs;
14742
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014743 // Now determine the memory trimming level of background processes.
14744 // Unfortunately we need to start at the back of the list to do this
14745 // properly. We only do this if the number of background apps we
14746 // are managing to keep around is less than half the maximum we desire;
14747 // if we are keeping a good number around, we'll let them use whatever
14748 // memory they want.
Dianne Hackborn7d608422011-08-07 16:24:18 -070014749 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/2)) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014750 final int N = mLruProcesses.size();
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014751 factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014752 int minFactor = 2;
14753 if (mHomeProcess != null) minFactor++;
14754 if (mPreviousProcess != null) minFactor++;
14755 if (factor < minFactor) factor = minFactor;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014756 step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014757 int fgTrimLevel;
14758 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/5)) {
14759 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
14760 } else if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/3)) {
14761 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
14762 } else {
14763 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
14764 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014765 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014766 for (i=0; i<N; i++) {
14767 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014768 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
14769 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080014770 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014771 if (app.trimMemoryLevel < curLevel && app.thread != null) {
14772 try {
14773 app.thread.scheduleTrimMemory(curLevel);
14774 } catch (RemoteException e) {
14775 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014776 if (false) {
14777 // For now we won't do this; our memory trimming seems
14778 // to be good enough at this point that destroying
14779 // activities causes more harm than good.
14780 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
14781 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014782 // Need to do this on its own message because the stack may not
14783 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014784 // For these apps we will also finish their activities
14785 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014786 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080014787 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014788 }
14789 }
14790 app.trimMemoryLevel = curLevel;
14791 step++;
14792 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014793 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014794 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014795 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
14796 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014797 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014798 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
14799 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014800 break;
14801 }
14802 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014803 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014804 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014805 && app.thread != null) {
14806 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014807 app.thread.scheduleTrimMemory(
14808 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014809 } catch (RemoteException e) {
14810 }
14811 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014812 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014813 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014814 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014815 && app.pendingUiClean) {
14816 // If this application is now in the background and it
14817 // had done UI, then give it the special trim level to
14818 // have it free UI resources.
14819 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
14820 if (app.trimMemoryLevel < level && app.thread != null) {
14821 try {
14822 app.thread.scheduleTrimMemory(level);
14823 } catch (RemoteException e) {
14824 }
14825 }
14826 app.pendingUiClean = false;
14827 }
14828 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014829 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014830 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014831 } catch (RemoteException e) {
14832 }
14833 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014834 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014835 }
14836 }
14837 } else {
14838 final int N = mLruProcesses.size();
14839 for (i=0; i<N; i++) {
14840 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070014841 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014842 && app.pendingUiClean) {
14843 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
14844 && app.thread != null) {
14845 try {
14846 app.thread.scheduleTrimMemory(
14847 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
14848 } catch (RemoteException e) {
14849 }
14850 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014851 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070014852 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080014853 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014854 }
14855 }
14856
14857 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070014858 // Need to do this on its own message because the stack may not
14859 // be in a consistent state at this point.
14860 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014862 }
14863
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070014864 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014865 synchronized (this) {
14866 int i;
14867
14868 // First remove any unused application processes whose package
14869 // has been removed.
14870 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
14871 final ProcessRecord app = mRemovedProcesses.get(i);
14872 if (app.activities.size() == 0
14873 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080014874 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014875 TAG, "Exiting empty application process "
14876 + app.processName + " ("
14877 + (app.thread != null ? app.thread.asBinder() : null)
14878 + ")\n");
14879 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070014880 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
14881 app.processName, app.setAdj, "empty");
14882 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014883 } else {
14884 try {
14885 app.thread.scheduleExit();
14886 } catch (Exception e) {
14887 // Ignore exceptions.
14888 }
14889 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070014890 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014891 mRemovedProcesses.remove(i);
14892
14893 if (app.persistent) {
14894 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080014895 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014896 }
14897 }
14898 }
14899 }
14900
Dianne Hackbornce86ba82011-07-13 19:33:41 -070014901 // Now update the oom adj for all processes.
14902 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014903 }
14904 }
14905
14906 /** This method sends the specified signal to each of the persistent apps */
14907 public void signalPersistentProcesses(int sig) throws RemoteException {
14908 if (sig != Process.SIGNAL_USR1) {
14909 throw new SecurityException("Only SIGNAL_USR1 is allowed");
14910 }
14911
14912 synchronized (this) {
14913 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
14914 != PackageManager.PERMISSION_GRANTED) {
14915 throw new SecurityException("Requires permission "
14916 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
14917 }
14918
Dianne Hackborndd71fc82009-12-16 19:24:32 -080014919 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
14920 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014921 if (r.thread != null && r.persistent) {
14922 Process.sendSignal(r.pid, sig);
14923 }
14924 }
14925 }
14926 }
14927
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014928 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
14929 if (proc == null || proc == mProfileProc) {
14930 proc = mProfileProc;
14931 path = mProfileFile;
14932 profileType = mProfileType;
14933 clearProfilerLocked();
14934 }
14935 if (proc == null) {
14936 return;
14937 }
14938 try {
14939 proc.thread.profilerControl(false, path, null, profileType);
14940 } catch (RemoteException e) {
14941 throw new IllegalStateException("Process disappeared");
14942 }
14943 }
14944
14945 private void clearProfilerLocked() {
14946 if (mProfileFd != null) {
14947 try {
14948 mProfileFd.close();
14949 } catch (IOException e) {
14950 }
14951 }
14952 mProfileApp = null;
14953 mProfileProc = null;
14954 mProfileFile = null;
14955 mProfileType = 0;
14956 mAutoStopProfiler = false;
14957 }
14958
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014959 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070014960 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014961
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014962 try {
14963 synchronized (this) {
14964 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
14965 // its own permission.
14966 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
14967 != PackageManager.PERMISSION_GRANTED) {
14968 throw new SecurityException("Requires permission "
14969 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014970 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014971
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014972 if (start && fd == null) {
14973 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080014974 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014975
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014976 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014977 if (process != null) {
14978 try {
14979 int pid = Integer.parseInt(process);
14980 synchronized (mPidsSelfLocked) {
14981 proc = mPidsSelfLocked.get(pid);
14982 }
14983 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014984 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014985
14986 if (proc == null) {
14987 HashMap<String, SparseArray<ProcessRecord>> all
14988 = mProcessNames.getMap();
14989 SparseArray<ProcessRecord> procs = all.get(process);
14990 if (procs != null && procs.size() > 0) {
14991 proc = procs.valueAt(0);
14992 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014993 }
14994 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014995
14996 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070014997 throw new IllegalArgumentException("Unknown process: " + process);
14998 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070014999
15000 if (start) {
15001 stopProfilerLocked(null, null, 0);
15002 setProfileApp(proc.info, proc.processName, path, fd, false);
15003 mProfileProc = proc;
15004 mProfileType = profileType;
15005 try {
15006 fd = fd.dup();
15007 } catch (IOException e) {
15008 fd = null;
15009 }
15010 proc.thread.profilerControl(start, path, fd, profileType);
15011 fd = null;
15012 mProfileFd = null;
15013 } else {
15014 stopProfilerLocked(proc, path, profileType);
15015 if (fd != null) {
15016 try {
15017 fd.close();
15018 } catch (IOException e) {
15019 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015020 }
15021 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070015022
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015023 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070015024 }
15025 } catch (RemoteException e) {
15026 throw new IllegalStateException("Process disappeared");
15027 } finally {
15028 if (fd != null) {
15029 try {
15030 fd.close();
15031 } catch (IOException e) {
15032 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080015033 }
15034 }
15035 }
Andy McFadden824c5102010-07-09 16:26:57 -070015036
15037 public boolean dumpHeap(String process, boolean managed,
15038 String path, ParcelFileDescriptor fd) throws RemoteException {
15039
15040 try {
15041 synchronized (this) {
15042 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
15043 // its own permission (same as profileControl).
15044 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
15045 != PackageManager.PERMISSION_GRANTED) {
15046 throw new SecurityException("Requires permission "
15047 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
15048 }
15049
15050 if (fd == null) {
15051 throw new IllegalArgumentException("null fd");
15052 }
15053
15054 ProcessRecord proc = null;
15055 try {
15056 int pid = Integer.parseInt(process);
15057 synchronized (mPidsSelfLocked) {
15058 proc = mPidsSelfLocked.get(pid);
15059 }
15060 } catch (NumberFormatException e) {
15061 }
15062
15063 if (proc == null) {
15064 HashMap<String, SparseArray<ProcessRecord>> all
15065 = mProcessNames.getMap();
15066 SparseArray<ProcessRecord> procs = all.get(process);
15067 if (procs != null && procs.size() > 0) {
15068 proc = procs.valueAt(0);
15069 }
15070 }
15071
15072 if (proc == null || proc.thread == null) {
15073 throw new IllegalArgumentException("Unknown process: " + process);
15074 }
15075
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080015076 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
15077 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070015078 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
15079 throw new SecurityException("Process not debuggable: " + proc);
15080 }
15081 }
15082
15083 proc.thread.dumpHeap(managed, path, fd);
15084 fd = null;
15085 return true;
15086 }
15087 } catch (RemoteException e) {
15088 throw new IllegalStateException("Process disappeared");
15089 } finally {
15090 if (fd != null) {
15091 try {
15092 fd.close();
15093 } catch (IOException e) {
15094 }
15095 }
15096 }
15097 }
15098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015099 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
15100 public void monitor() {
15101 synchronized (this) { }
15102 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080015103
Dianne Hackborna573f6a2012-02-09 16:12:18 -080015104 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080015105 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
15106 ProcessRecord processRecord = mLruProcesses.get(i);
15107 try {
15108 if (processRecord.thread != null) {
15109 processRecord.thread.setCoreSettings(settings);
15110 }
15111 } catch (RemoteException re) {
15112 /* ignore */
15113 }
15114 }
15115 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015116
15117 // Multi-user methods
15118
Amith Yamasani742a6712011-05-04 14:49:28 -070015119 private int mCurrentUserId;
15120 private SparseIntArray mLoggedInUsers = new SparseIntArray(5);
15121
15122 public boolean switchUser(int userId) {
15123 final int callingUid = Binder.getCallingUid();
15124 if (callingUid != 0 && callingUid != Process.myUid()) {
15125 Slog.e(TAG, "Trying to switch user from unauthorized app");
15126 return false;
15127 }
15128 if (mCurrentUserId == userId)
15129 return true;
15130
15131 synchronized (this) {
15132 // Check if user is already logged in, otherwise check if user exists first before
15133 // adding to the list of logged in users.
15134 if (mLoggedInUsers.indexOfKey(userId) < 0) {
15135 if (!userExists(userId)) {
15136 return false;
15137 }
15138 mLoggedInUsers.append(userId, userId);
15139 }
15140
15141 mCurrentUserId = userId;
15142 boolean haveActivities = mMainStack.switchUser(userId);
15143 if (!haveActivities) {
15144 startHomeActivityLocked(userId);
15145 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080015146
Amith Yamasani37ce3a82012-02-06 12:04:42 -080015147 }
Amith Yamasani13593602012-03-22 16:16:17 -070015148
15149 // Inform of user switch
15150 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
15151 addedIntent.putExtra(Intent.EXTRA_USERID, userId);
15152 mContext.sendBroadcast(addedIntent, android.Manifest.permission.MANAGE_ACCOUNTS);
15153
Amith Yamasani4b2e9342011-03-31 12:38:53 -070015154 return true;
15155 }
Amith Yamasani742a6712011-05-04 14:49:28 -070015156
Amith Yamasani52f1d752012-03-28 18:19:29 -070015157 @Override
15158 public UserInfo getCurrentUser() throws RemoteException {
15159 final int callingUid = Binder.getCallingUid();
15160 if (callingUid != 0 && callingUid != Process.myUid()) {
15161 Slog.e(TAG, "Trying to get user from unauthorized app");
15162 return null;
15163 }
15164 return AppGlobals.getPackageManager().getUser(mCurrentUserId);
15165 }
15166
Amith Yamasani13593602012-03-22 16:16:17 -070015167 private void onUserRemoved(Intent intent) {
15168 int extraUserId = intent.getIntExtra(Intent.EXTRA_USERID, -1);
15169 if (extraUserId < 1) return;
15170
15171 // Kill all the processes for the user
15172 ArrayList<Pair<String, Integer>> pkgAndUids = new ArrayList<Pair<String,Integer>>();
15173 synchronized (this) {
15174 HashMap<String,SparseArray<ProcessRecord>> map = mProcessNames.getMap();
15175 for (Entry<String, SparseArray<ProcessRecord>> uidMap : map.entrySet()) {
15176 SparseArray<ProcessRecord> uids = uidMap.getValue();
15177 for (int i = 0; i < uids.size(); i++) {
15178 if (UserId.getUserId(uids.keyAt(i)) == extraUserId) {
15179 pkgAndUids.add(new Pair<String,Integer>(uidMap.getKey(), uids.keyAt(i)));
15180 }
15181 }
15182 }
15183
15184 for (Pair<String,Integer> pkgAndUid : pkgAndUids) {
15185 forceStopPackageLocked(pkgAndUid.first, pkgAndUid.second,
15186 false, false, true, true, extraUserId);
15187 }
15188 }
15189 }
15190
Amith Yamasani742a6712011-05-04 14:49:28 -070015191 private boolean userExists(int userId) {
15192 try {
Amith Yamasani13593602012-03-22 16:16:17 -070015193 UserInfo user = AppGlobals.getPackageManager().getUser(userId);
15194 return user != null;
Amith Yamasani742a6712011-05-04 14:49:28 -070015195 } catch (RemoteException re) {
15196 // Won't happen, in same process
15197 }
15198
15199 return false;
15200 }
15201
Amith Yamasani37ce3a82012-02-06 12:04:42 -080015202 private void checkValidCaller(int uid, int userId) {
15203 if (UserId.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
15204
15205 throw new SecurityException("Caller uid=" + uid
15206 + " is not privileged to communicate with user=" + userId);
15207 }
Amith Yamasani742a6712011-05-04 14:49:28 -070015208
15209 private int applyUserId(int uid, int userId) {
15210 return UserId.getUid(userId, uid);
15211 }
15212
15213 private ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080015214 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070015215 ApplicationInfo newInfo = new ApplicationInfo(info);
15216 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070015217 newInfo.dataDir = USER_DATA_DIR + userId + "/"
15218 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070015219 return newInfo;
15220 }
15221
15222 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070015223 if (aInfo == null
15224 || (userId < 1 && aInfo.applicationInfo.uid < UserId.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070015225 return aInfo;
15226 }
15227
15228 ActivityInfo info = new ActivityInfo(aInfo);
15229 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
15230 return info;
15231 }
15232
15233 static class ServiceMap {
15234
15235 private final SparseArray<HashMap<ComponentName, ServiceRecord>> mServicesByNamePerUser
15236 = new SparseArray<HashMap<ComponentName, ServiceRecord>>();
15237 private final SparseArray<HashMap<Intent.FilterComparison, ServiceRecord>>
15238 mServicesByIntentPerUser = new SparseArray<
15239 HashMap<Intent.FilterComparison, ServiceRecord>>();
15240
15241 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
15242 // TODO: Deal with global services
15243 if (DEBUG_MU)
15244 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
15245 return getServices(callingUser).get(name);
15246 }
15247
15248 ServiceRecord getServiceByName(ComponentName name) {
15249 return getServiceByName(name, -1);
15250 }
15251
15252 ServiceRecord getServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15253 // TODO: Deal with global services
15254 if (DEBUG_MU)
15255 Slog.v(TAG_MU, "getServiceByIntent(" + filter + "), callingUser = " + callingUser);
15256 return getServicesByIntent(callingUser).get(filter);
15257 }
15258
15259 ServiceRecord getServiceByIntent(Intent.FilterComparison filter) {
15260 return getServiceByIntent(filter, -1);
15261 }
15262
15263 void putServiceByName(ComponentName name, int callingUser, ServiceRecord value) {
15264 // TODO: Deal with global services
15265 getServices(callingUser).put(name, value);
15266 }
15267
15268 void putServiceByIntent(Intent.FilterComparison filter, int callingUser,
15269 ServiceRecord value) {
15270 // TODO: Deal with global services
15271 getServicesByIntent(callingUser).put(filter, value);
15272 }
15273
15274 void removeServiceByName(ComponentName name, int callingUser) {
15275 // TODO: Deal with global services
15276 ServiceRecord removed = getServices(callingUser).remove(name);
15277 if (DEBUG_MU)
15278 Slog.v(TAG, "removeServiceByName user=" + callingUser + " name=" + name
15279 + " removed=" + removed);
15280 }
15281
15282 void removeServiceByIntent(Intent.FilterComparison filter, int callingUser) {
15283 // TODO: Deal with global services
15284 ServiceRecord removed = getServicesByIntent(callingUser).remove(filter);
15285 if (DEBUG_MU)
15286 Slog.v(TAG_MU, "removeServiceByIntent user=" + callingUser + " intent=" + filter
15287 + " removed=" + removed);
15288 }
15289
15290 Collection<ServiceRecord> getAllServices(int callingUser) {
15291 // TODO: Deal with global services
15292 return getServices(callingUser).values();
15293 }
15294
15295 private HashMap<ComponentName, ServiceRecord> getServices(int callingUser) {
15296 HashMap map = mServicesByNamePerUser.get(callingUser);
15297 if (map == null) {
15298 map = new HashMap<ComponentName, ServiceRecord>();
15299 mServicesByNamePerUser.put(callingUser, map);
15300 }
15301 return map;
15302 }
15303
15304 private HashMap<Intent.FilterComparison, ServiceRecord> getServicesByIntent(
15305 int callingUser) {
15306 HashMap map = mServicesByIntentPerUser.get(callingUser);
15307 if (map == null) {
15308 map = new HashMap<Intent.FilterComparison, ServiceRecord>();
15309 mServicesByIntentPerUser.put(callingUser, map);
15310 }
15311 return map;
15312 }
15313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080015314}