blob: db2ec5b6d4e1181249587b07b02611f2538966d9 [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;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070049import android.app.IStopUserCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.app.IThumbnailReceiver;
51import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070052import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070053import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.app.PendingIntent;
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;
Amith Yamasani258848d2012-08-10 17:06:33 -070079import android.content.pm.UserInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070080import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070081import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.content.pm.ProviderInfo;
83import android.content.pm.ResolveInfo;
84import android.content.pm.ServiceInfo;
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;
rpcraigec7ed14c2012-07-25 13:10:37 -0400109import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700111import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.os.SystemClock;
113import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700114import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700115import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700117import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800119import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700120import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700122import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700124import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700125import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126import android.view.Gravity;
127import android.view.LayoutInflater;
128import android.view.View;
129import android.view.WindowManager;
130import android.view.WindowManagerPolicy;
131
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700132import java.io.BufferedInputStream;
133import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700134import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700135import java.io.DataInputStream;
136import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.File;
138import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700139import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700141import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200142import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800143import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700145import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146import java.lang.ref.WeakReference;
147import java.util.ArrayList;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700148import java.util.Collections;
149import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150import java.util.HashMap;
151import java.util.HashSet;
152import java.util.Iterator;
153import java.util.List;
154import java.util.Locale;
155import java.util.Map;
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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // How long we wait until we timeout on key dispatching.
245 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 // How long we wait until we timeout on key dispatching during instrumentation.
248 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
249
Dan Egnor42471dd2010-01-07 17:25:22 -0800250 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251
252 static final String[] EMPTY_STRING_ARRAY = new String[0];
253
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700254 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700255
256 private final boolean mHeadless;
257
Joe Onorato54a4a412011-11-02 20:50:08 -0700258 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
259 // default actuion automatically. Important for devices without direct input
260 // devices.
261 private boolean mShowDialogs = true;
262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800263 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700264 * Description of a request to start a new activity, which has been held
265 * due to app switches being disabled.
266 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700267 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700268 ActivityRecord r;
269 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700270 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700271 }
272
273 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
274 = new ArrayList<PendingActivityLaunch>();
275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800276
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800277 BroadcastQueue mFgBroadcastQueue;
278 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800279 // Convenient for easy iteration over the queues. Foreground is first
280 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800281 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800282
283 BroadcastQueue broadcastQueueForIntent(Intent intent) {
284 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
285 if (DEBUG_BACKGROUND_BROADCAST) {
286 Slog.i(TAG, "Broadcast intent " + intent + " on "
287 + (isFg ? "foreground" : "background")
288 + " queue");
289 }
290 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
291 }
292
293 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
294 for (BroadcastQueue queue : mBroadcastQueues) {
295 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
296 if (r != null) {
297 return r;
298 }
299 }
300 return null;
301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302
303 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 * Activity we have told the window manager to have key focus.
305 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700306 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700307 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 * List of intents that were used to start the most recent tasks.
309 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700310 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311
312 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700313 * Process management.
314 */
315 final ProcessList mProcessList = new ProcessList();
316
317 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 * All of the applications we currently have running organized by name.
319 * The keys are strings of the application package name (as
320 * returned by the package manager), and the keys are ApplicationRecord
321 * objects.
322 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700323 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324
325 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800326 * The currently running isolated processes.
327 */
328 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
329
330 /**
331 * Counter for assigning isolated process uids, to avoid frequently reusing the
332 * same ones.
333 */
334 int mNextIsolatedProcessUid = 0;
335
336 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700337 * The currently running heavy-weight process, if any.
338 */
339 ProcessRecord mHeavyWeightProcess = null;
340
341 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800342 * The last time that various processes have crashed.
343 */
344 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
345
346 /**
347 * Set of applications that we consider to be bad, and will reject
348 * incoming broadcasts from (which the user has no control over).
349 * Processes are added to this set when they have crashed twice within
350 * a minimum amount of time; they are removed from it when they are
351 * later restarted (hopefully due to some user action). The value is the
352 * time it was added to the list.
353 */
354 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
355
356 /**
357 * All of the processes we currently have running organized by pid.
358 * The keys are the pid running the application.
359 *
360 * <p>NOTE: This object is protected by its own lock, NOT the global
361 * activity manager lock!
362 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700363 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800364
365 /**
366 * All of the processes that have been forced to be foreground. The key
367 * is the pid of the caller who requested it (we hold a death
368 * link on it).
369 */
370 abstract class ForegroundToken implements IBinder.DeathRecipient {
371 int pid;
372 IBinder token;
373 }
374 final SparseArray<ForegroundToken> mForegroundProcesses
375 = new SparseArray<ForegroundToken>();
376
377 /**
378 * List of records for processes that someone had tried to start before the
379 * system was ready. We don't start them at that point, but ensure they
380 * are started by the time booting is complete.
381 */
382 final ArrayList<ProcessRecord> mProcessesOnHold
383 = new ArrayList<ProcessRecord>();
384
385 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800386 * List of persistent applications that are in the process
387 * of being started.
388 */
389 final ArrayList<ProcessRecord> mPersistentStartingProcesses
390 = new ArrayList<ProcessRecord>();
391
392 /**
393 * Processes that are being forcibly torn down.
394 */
395 final ArrayList<ProcessRecord> mRemovedProcesses
396 = new ArrayList<ProcessRecord>();
397
398 /**
399 * List of running applications, sorted by recent usage.
400 * The first entry in the list is the least recently used.
401 * It contains ApplicationRecord objects. This list does NOT include
402 * any persistent application records (since we never want to exit them).
403 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800404 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800405 = new ArrayList<ProcessRecord>();
406
407 /**
408 * List of processes that should gc as soon as things are idle.
409 */
410 final ArrayList<ProcessRecord> mProcessesToGc
411 = new ArrayList<ProcessRecord>();
412
413 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800414 * This is the process holding what we currently consider to be
415 * the "home" activity.
416 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700417 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800418
419 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700420 * This is the process holding the activity the user last visited that
421 * is in a different process from the one they are currently in.
422 */
423 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800424
425 /**
426 * The time at which the previous process was last visible.
427 */
428 long mPreviousProcessVisibleTime;
429
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700430 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700431 * Which uses have been started, so are allowed to run code.
432 */
433 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
434
435 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400436 * Packages that the user has asked to have run in screen size
437 * compatibility mode instead of filling the screen.
438 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700439 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400440
441 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442 * Set of PendingResultRecord objects that are currently active.
443 */
444 final HashSet mPendingResultRecords = new HashSet();
445
446 /**
447 * Set of IntentSenderRecord objects that are currently active.
448 */
449 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
450 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
451
452 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800453 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700454 * already logged DropBox entries for. Guarded by itself. If
455 * something (rogue user app) forces this over
456 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
457 */
458 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
459 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
460
461 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700462 * Strict Mode background batched logging state.
463 *
464 * The string buffer is guarded by itself, and its lock is also
465 * used to determine if another batched write is already
466 * in-flight.
467 */
468 private final StringBuilder mStrictModeBuffer = new StringBuilder();
469
470 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 * Keeps track of all IIntentReceivers that have been registered for
472 * broadcasts. Hash keys are the receiver IBinder, hash value is
473 * a ReceiverList.
474 */
475 final HashMap mRegisteredReceivers = new HashMap();
476
477 /**
478 * Resolver for broadcast intents to registered receivers.
479 * Holds BroadcastFilter (subclass of IntentFilter).
480 */
481 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
482 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
483 @Override
484 protected boolean allowFilterResult(
485 BroadcastFilter filter, List<BroadcastFilter> dest) {
486 IBinder target = filter.receiverList.receiver.asBinder();
487 for (int i=dest.size()-1; i>=0; i--) {
488 if (dest.get(i).receiverList.receiver.asBinder() == target) {
489 return false;
490 }
491 }
492 return true;
493 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700494
495 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700496 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700497 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
498 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700499 return super.newResult(filter, match, userId);
500 }
501 return null;
502 }
503
504 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700505 protected BroadcastFilter[] newArray(int size) {
506 return new BroadcastFilter[size];
507 }
508
509 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700510 protected String packageForFilter(BroadcastFilter filter) {
511 return filter.packageName;
512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 };
514
515 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700516 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700518 * that action (which should usually be one). The SparseArray is keyed
519 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
520 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700522 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
523 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700525 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526
527 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700528 * Backup/restore process management
529 */
530 String mBackupAppName = null;
531 BackupRecord mBackupTarget = null;
532
533 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 * List of PendingThumbnailsRecord objects of clients who are still
535 * waiting to receive all of the thumbnails for a task.
536 */
537 final ArrayList mPendingThumbnails = new ArrayList();
538
539 /**
540 * List of HistoryRecord objects that have been finished and must
541 * still report back to a pending thumbnail receiver.
542 */
543 final ArrayList mCancelledThumbnails = new ArrayList();
544
Amith Yamasani742a6712011-05-04 14:49:28 -0700545 final ProviderMap mProviderMap = new ProviderMap();
546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 /**
548 * List of content providers who have clients waiting for them. The
549 * application is currently being launched and the provider will be
550 * removed from this list once it is published.
551 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700552 final ArrayList<ContentProviderRecord> mLaunchingProviders
553 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554
555 /**
556 * Global set of specific Uri permissions that have been granted.
557 */
558 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
559 = new SparseArray<HashMap<Uri, UriPermission>>();
560
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800561 CoreSettingsObserver mCoreSettingsObserver;
562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 /**
564 * Thread-local storage used to carry caller permissions over through
565 * indirect content-provider access.
566 * @see #ActivityManagerService.openContentUri()
567 */
568 private class Identity {
569 public int pid;
570 public int uid;
571
572 Identity(int _pid, int _uid) {
573 pid = _pid;
574 uid = _uid;
575 }
576 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
579
580 /**
581 * All information we have collected about the runtime performance of
582 * any user id that can impact battery performance.
583 */
584 final BatteryStatsService mBatteryStatsService;
585
586 /**
587 * information about component usage
588 */
589 final UsageStatsService mUsageStatsService;
590
591 /**
592 * Current configuration information. HistoryRecord objects are given
593 * a reference to this object to indicate which configuration they are
594 * currently running in, so this object must be kept immutable.
595 */
596 Configuration mConfiguration = new Configuration();
597
598 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800599 * Current sequencing integer of the configuration, for skipping old
600 * configurations.
601 */
602 int mConfigurationSeq = 0;
603
604 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700605 * Hardware-reported OpenGLES version.
606 */
607 final int GL_ES_VERSION;
608
609 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 * List of initialization arguments to pass to all processes when binding applications to them.
611 * For example, references to the commonly used services.
612 */
613 HashMap<String, IBinder> mAppBindArgs;
614
615 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700616 * Temporary to avoid allocations. Protected by main lock.
617 */
618 final StringBuilder mStringBuilder = new StringBuilder(256);
619
620 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 * Used to control how we initialize the service.
622 */
623 boolean mStartRunning = false;
624 ComponentName mTopComponent;
625 String mTopAction;
626 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700627 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 boolean mSystemReady = false;
629 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700630 boolean mWaitingUpdate = false;
631 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700632 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700633 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634
635 Context mContext;
636
637 int mFactoryTest;
638
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700639 boolean mCheckedForSetup;
640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700642 * The time at which we will allow normal application switches again,
643 * after a call to {@link #stopAppSwitches()}.
644 */
645 long mAppSwitchesAllowedTime;
646
647 /**
648 * This is set to true after the first switch after mAppSwitchesAllowedTime
649 * is set; any switches after that will clear the time.
650 */
651 boolean mDidAppSwitch;
652
653 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700654 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700655 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700656 long mLastPowerCheckRealtime;
657
658 /**
659 * Last time (in uptime) at which we checked for power usage.
660 */
661 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700662
663 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 * Set while we are wanting to sleep, to prevent any
665 * activities from being started/resumed.
666 */
667 boolean mSleeping = false;
668
669 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700670 * State of external calls telling us if the device is asleep.
671 */
672 boolean mWentToSleep = false;
673
674 /**
675 * State of external call telling us if the lock screen is shown.
676 */
677 boolean mLockScreenShown = false;
678
679 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700680 * Set if we are shutting down the system, similar to sleeping.
681 */
682 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683
684 /**
685 * Task identifier that activities are currently being started
686 * in. Incremented each time a new task is created.
687 * todo: Replace this with a TokenSpace class that generates non-repeating
688 * integers that won't wrap.
689 */
690 int mCurTask = 1;
691
692 /**
693 * Current sequence id for oom_adj computation traversal.
694 */
695 int mAdjSeq = 0;
696
697 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700698 * Current sequence id for process LRU updating.
699 */
700 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701
702 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700703 * Keep track of the non-hidden/empty process we last found, to help
704 * determine how to distribute hidden/empty processes next time.
705 */
706 int mNumNonHiddenProcs = 0;
707
708 /**
709 * Keep track of the number of hidden procs, to balance oom adj
710 * distribution between those and empty procs.
711 */
712 int mNumHiddenProcs = 0;
713
714 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700715 * Keep track of the number of service processes we last found, to
716 * determine on the next iteration which should be B services.
717 */
718 int mNumServiceProcs = 0;
719 int mNewNumServiceProcs = 0;
720
721 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 * System monitoring: number of processes that died since the last
723 * N procs were started.
724 */
725 int[] mProcDeaths = new int[20];
726
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700727 /**
728 * This is set if we had to do a delayed dexopt of an app before launching
729 * it, to increasing the ANR timeouts in that case.
730 */
731 boolean mDidDexOpt;
732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 String mDebugApp = null;
734 boolean mWaitForDebugger = false;
735 boolean mDebugTransient = false;
736 String mOrigDebugApp = null;
737 boolean mOrigWaitForDebugger = false;
738 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700739 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700740 String mProfileApp = null;
741 ProcessRecord mProfileProc = null;
742 String mProfileFile;
743 ParcelFileDescriptor mProfileFd;
744 int mProfileType = 0;
745 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800746 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700748 static class ProcessChangeItem {
749 static final int CHANGE_ACTIVITIES = 1<<0;
750 static final int CHANGE_IMPORTANCE= 1<<1;
751 int changes;
752 int uid;
753 int pid;
754 int importance;
755 boolean foregroundActivities;
756 }
757
Jeff Sharkeya4620792011-05-20 15:29:23 -0700758 final RemoteCallbackList<IProcessObserver> mProcessObservers
759 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700760 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
761
762 final ArrayList<ProcessChangeItem> mPendingProcessChanges
763 = new ArrayList<ProcessChangeItem>();
764 final ArrayList<ProcessChangeItem> mAvailProcessChanges
765 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 /**
768 * Callback of last caller to {@link #requestPss}.
769 */
770 Runnable mRequestPssCallback;
771
772 /**
773 * Remaining processes for which we are waiting results from the last
774 * call to {@link #requestPss}.
775 */
776 final ArrayList<ProcessRecord> mRequestPssList
777 = new ArrayList<ProcessRecord>();
778
779 /**
780 * Runtime statistics collection thread. This object's lock is used to
781 * protect all related state.
782 */
783 final Thread mProcessStatsThread;
784
785 /**
786 * Used to collect process stats when showing not responding dialog.
787 * Protected by mProcessStatsThread.
788 */
789 final ProcessStats mProcessStats = new ProcessStats(
790 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700791 final AtomicLong mLastCpuTime = new AtomicLong(0);
792 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 long mLastWriteTime = 0;
795
796 /**
797 * Set to true after the system has finished booting.
798 */
799 boolean mBooted = false;
800
Dianne Hackborn7d608422011-08-07 16:24:18 -0700801 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700802 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803
804 WindowManagerService mWindowManager;
805
806 static ActivityManagerService mSelf;
807 static ActivityThread mSystemThread;
808
Amith Yamasani258848d2012-08-10 17:06:33 -0700809 private int mCurrentUserId;
Amith Yamasani258848d2012-08-10 17:06:33 -0700810 private UserManager mUserManager;
811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 private final class AppDeathRecipient implements IBinder.DeathRecipient {
813 final ProcessRecord mApp;
814 final int mPid;
815 final IApplicationThread mAppThread;
816
817 AppDeathRecipient(ProcessRecord app, int pid,
818 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800819 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 TAG, "New death recipient " + this
821 + " for thread " + thread.asBinder());
822 mApp = app;
823 mPid = pid;
824 mAppThread = thread;
825 }
826
827 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800828 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 TAG, "Death received in " + this
830 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 synchronized(ActivityManagerService.this) {
832 appDiedLocked(mApp, mPid, mAppThread);
833 }
834 }
835 }
836
837 static final int SHOW_ERROR_MSG = 1;
838 static final int SHOW_NOT_RESPONDING_MSG = 2;
839 static final int SHOW_FACTORY_ERROR_MSG = 3;
840 static final int UPDATE_CONFIGURATION_MSG = 4;
841 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
842 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 static final int SERVICE_TIMEOUT_MSG = 12;
844 static final int UPDATE_TIME_ZONE = 13;
845 static final int SHOW_UID_ERROR_MSG = 14;
846 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700848 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700849 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800850 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700851 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
852 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700853 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700854 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700855 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700856 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700857 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700858 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700859 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700860 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800862 static final int FIRST_ACTIVITY_STACK_MSG = 100;
863 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
864 static final int FIRST_COMPAT_MODE_MSG = 300;
865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700867 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700868 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869
870 final Handler mHandler = new Handler() {
871 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800872 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 //}
874
875 public void handleMessage(Message msg) {
876 switch (msg.what) {
877 case SHOW_ERROR_MSG: {
878 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 synchronized (ActivityManagerService.this) {
880 ProcessRecord proc = (ProcessRecord)data.get("app");
881 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800882 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 return;
884 }
885 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700886 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800887 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 d.show();
889 proc.crashDialog = d;
890 } else {
891 // The device is asleep, so just pretend that the user
892 // saw a crash dialog and hit "force quit".
893 res.set(0);
894 }
895 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700896
897 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 } break;
899 case SHOW_NOT_RESPONDING_MSG: {
900 synchronized (ActivityManagerService.this) {
901 HashMap data = (HashMap) msg.obj;
902 ProcessRecord proc = (ProcessRecord)data.get("app");
903 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800904 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 return;
906 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800907
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700908 Intent intent = new Intent("android.intent.action.ANR");
909 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800910 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
911 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700912 }
913 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800914 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700915 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800916
Justin Kohbc52ca22012-03-29 15:11:44 -0700917 if (mShowDialogs) {
918 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700919 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700920 d.show();
921 proc.anrDialog = d;
922 } else {
923 // Just kill the app if there is no dialog to be shown.
924 killAppAtUsersRequest(proc, null);
925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700927
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700928 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700930 case SHOW_STRICT_MODE_VIOLATION_MSG: {
931 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
932 synchronized (ActivityManagerService.this) {
933 ProcessRecord proc = (ProcessRecord) data.get("app");
934 if (proc == null) {
935 Slog.e(TAG, "App not found when showing strict mode dialog.");
936 break;
937 }
938 if (proc.crashDialog != null) {
939 Slog.e(TAG, "App already has strict mode dialog: " + proc);
940 return;
941 }
942 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700943 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700944 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
945 d.show();
946 proc.crashDialog = d;
947 } else {
948 // The device is asleep, so just pretend that the user
949 // saw a crash dialog and hit "force quit".
950 res.set(0);
951 }
952 }
953 ensureBootCompleted();
954 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 case SHOW_FACTORY_ERROR_MSG: {
956 Dialog d = new FactoryErrorDialog(
957 mContext, msg.getData().getCharSequence("msg"));
958 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700959 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 } break;
961 case UPDATE_CONFIGURATION_MSG: {
962 final ContentResolver resolver = mContext.getContentResolver();
963 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
964 } break;
965 case GC_BACKGROUND_PROCESSES_MSG: {
966 synchronized (ActivityManagerService.this) {
967 performAppGcsIfAppropriateLocked();
968 }
969 } break;
970 case WAIT_FOR_DEBUGGER_MSG: {
971 synchronized (ActivityManagerService.this) {
972 ProcessRecord app = (ProcessRecord)msg.obj;
973 if (msg.arg1 != 0) {
974 if (!app.waitedForDebugger) {
975 Dialog d = new AppWaitingForDebuggerDialog(
976 ActivityManagerService.this,
977 mContext, app);
978 app.waitDialog = d;
979 app.waitedForDebugger = true;
980 d.show();
981 }
982 } else {
983 if (app.waitDialog != null) {
984 app.waitDialog.dismiss();
985 app.waitDialog = null;
986 }
987 }
988 }
989 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700991 if (mDidDexOpt) {
992 mDidDexOpt = false;
993 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
994 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700995 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700996 return;
997 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700998 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 } break;
1000 case UPDATE_TIME_ZONE: {
1001 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001002 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1003 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 if (r.thread != null) {
1005 try {
1006 r.thread.updateTimeZone();
1007 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001008 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 }
1010 }
1011 }
1012 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001013 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001014 case CLEAR_DNS_CACHE: {
1015 synchronized (ActivityManagerService.this) {
1016 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1017 ProcessRecord r = mLruProcesses.get(i);
1018 if (r.thread != null) {
1019 try {
1020 r.thread.clearDnsCache();
1021 } catch (RemoteException ex) {
1022 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1023 }
1024 }
1025 }
1026 }
1027 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001028 case UPDATE_HTTP_PROXY: {
1029 ProxyProperties proxy = (ProxyProperties)msg.obj;
1030 String host = "";
1031 String port = "";
1032 String exclList = "";
1033 if (proxy != null) {
1034 host = proxy.getHost();
1035 port = Integer.toString(proxy.getPort());
1036 exclList = proxy.getExclusionList();
1037 }
1038 synchronized (ActivityManagerService.this) {
1039 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1040 ProcessRecord r = mLruProcesses.get(i);
1041 if (r.thread != null) {
1042 try {
1043 r.thread.setHttpProxy(host, port, exclList);
1044 } catch (RemoteException ex) {
1045 Slog.w(TAG, "Failed to update http proxy for: " +
1046 r.info.processName);
1047 }
1048 }
1049 }
1050 }
1051 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001053 String title = "System UIDs Inconsistent";
1054 String text = "UIDs on the system are inconsistent, you need to wipe your"
1055 + " data partition or your device will be unstable.";
1056 Log.e(TAG, title + ": " + text);
1057 if (mShowDialogs) {
1058 // XXX This is a temporary dialog, no need to localize.
1059 AlertDialog d = new BaseErrorDialog(mContext);
1060 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1061 d.setCancelable(false);
1062 d.setTitle(title);
1063 d.setMessage(text);
1064 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1065 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1066 mUidAlert = d;
1067 d.show();
1068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 } break;
1070 case IM_FEELING_LUCKY_MSG: {
1071 if (mUidAlert != null) {
1072 mUidAlert.dismiss();
1073 mUidAlert = null;
1074 }
1075 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001077 if (mDidDexOpt) {
1078 mDidDexOpt = false;
1079 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1080 nmsg.obj = msg.obj;
1081 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1082 return;
1083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 ProcessRecord app = (ProcessRecord)msg.obj;
1085 synchronized (ActivityManagerService.this) {
1086 processStartTimedOutLocked(app);
1087 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001088 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001089 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1090 synchronized (ActivityManagerService.this) {
1091 doPendingActivityLaunchesLocked(true);
1092 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001093 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001094 case KILL_APPLICATION_MSG: {
1095 synchronized (ActivityManagerService.this) {
1096 int uid = msg.arg1;
1097 boolean restart = (msg.arg2 == 1);
1098 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001099 forceStopPackageLocked(pkg, uid, restart, false, true, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001100 UserHandle.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001101 }
1102 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001103 case FINALIZE_PENDING_INTENT_MSG: {
1104 ((PendingIntentRecord)msg.obj).completeFinalize();
1105 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001106 case POST_HEAVY_NOTIFICATION_MSG: {
1107 INotificationManager inm = NotificationManager.getService();
1108 if (inm == null) {
1109 return;
1110 }
1111
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001112 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001113 ProcessRecord process = root.app;
1114 if (process == null) {
1115 return;
1116 }
1117
1118 try {
1119 Context context = mContext.createPackageContext(process.info.packageName, 0);
1120 String text = mContext.getString(R.string.heavy_weight_notification,
1121 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1122 Notification notification = new Notification();
1123 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1124 notification.when = 0;
1125 notification.flags = Notification.FLAG_ONGOING_EVENT;
1126 notification.tickerText = text;
1127 notification.defaults = 0; // please be quiet
1128 notification.sound = null;
1129 notification.vibrate = null;
1130 notification.setLatestEventInfo(context, text,
1131 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001132 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1133 PendingIntent.FLAG_CANCEL_CURRENT, null,
1134 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001135
1136 try {
1137 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001138 inm.enqueueNotificationWithTag("android", null,
1139 R.string.heavy_weight_notification,
1140 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001141 } catch (RuntimeException e) {
1142 Slog.w(ActivityManagerService.TAG,
1143 "Error showing notification for heavy-weight app", e);
1144 } catch (RemoteException e) {
1145 }
1146 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001147 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001148 }
1149 } break;
1150 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1151 INotificationManager inm = NotificationManager.getService();
1152 if (inm == null) {
1153 return;
1154 }
1155 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001156 inm.cancelNotificationWithTag("android", null,
1157 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001158 } catch (RuntimeException e) {
1159 Slog.w(ActivityManagerService.TAG,
1160 "Error canceling notification for service", e);
1161 } catch (RemoteException e) {
1162 }
1163 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001164 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1165 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001166 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001167 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001168 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1169 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001170 }
1171 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001172 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1173 synchronized (ActivityManagerService.this) {
1174 ActivityRecord ar = (ActivityRecord)msg.obj;
1175 if (mCompatModeDialog != null) {
1176 if (mCompatModeDialog.mAppInfo.packageName.equals(
1177 ar.info.applicationInfo.packageName)) {
1178 return;
1179 }
1180 mCompatModeDialog.dismiss();
1181 mCompatModeDialog = null;
1182 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001183 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001184 if (mCompatModePackages.getPackageAskCompatModeLocked(
1185 ar.packageName)) {
1186 int mode = mCompatModePackages.computeCompatModeLocked(
1187 ar.info.applicationInfo);
1188 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1189 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1190 mCompatModeDialog = new CompatModeDialog(
1191 ActivityManagerService.this, mContext,
1192 ar.info.applicationInfo);
1193 mCompatModeDialog.show();
1194 }
1195 }
1196 }
1197 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001198 break;
1199 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001200 case DISPATCH_PROCESSES_CHANGED: {
1201 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001202 break;
1203 }
1204 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001205 final int pid = msg.arg1;
1206 final int uid = msg.arg2;
1207 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001208 break;
1209 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001210 case REPORT_MEM_USAGE: {
1211 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1212 if (!isDebuggable) {
1213 return;
1214 }
1215 synchronized (ActivityManagerService.this) {
1216 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001217 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1218 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001219 // avoid spamming.
1220 return;
1221 }
1222 mLastMemUsageReportTime = now;
1223 }
1224 Thread thread = new Thread() {
1225 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001226 StringBuilder dropBuilder = new StringBuilder(1024);
1227 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001228 StringWriter oomSw = new StringWriter();
1229 PrintWriter oomPw = new PrintWriter(oomSw);
1230 StringWriter catSw = new StringWriter();
1231 PrintWriter catPw = new PrintWriter(catSw);
1232 String[] emptyArgs = new String[] { };
1233 StringBuilder tag = new StringBuilder(128);
1234 StringBuilder stack = new StringBuilder(128);
1235 tag.append("Low on memory -- ");
1236 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1237 tag, stack);
1238 dropBuilder.append(stack);
1239 dropBuilder.append('\n');
1240 dropBuilder.append('\n');
1241 String oomString = oomSw.toString();
1242 dropBuilder.append(oomString);
1243 dropBuilder.append('\n');
1244 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001245 try {
1246 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1247 "procrank", });
1248 final InputStreamReader converter = new InputStreamReader(
1249 proc.getInputStream());
1250 BufferedReader in = new BufferedReader(converter);
1251 String line;
1252 while (true) {
1253 line = in.readLine();
1254 if (line == null) {
1255 break;
1256 }
1257 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001258 logBuilder.append(line);
1259 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001260 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001261 dropBuilder.append(line);
1262 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001263 }
1264 converter.close();
1265 } catch (IOException e) {
1266 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001267 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001268 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001269 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001270 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001271 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1272 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001273 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001274 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001275 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001276 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001277 addErrorToDropBox("lowmem", null, "system_server", null,
1278 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001279 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001280 synchronized (ActivityManagerService.this) {
1281 long now = SystemClock.uptimeMillis();
1282 if (mLastMemUsageReportTime < now) {
1283 mLastMemUsageReportTime = now;
1284 }
1285 }
1286 }
1287 };
1288 thread.start();
1289 break;
1290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 }
1292 }
1293 };
1294
1295 public static void setSystemProcess() {
1296 try {
1297 ActivityManagerService m = mSelf;
1298
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001299 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001301 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001302 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 if (MONITOR_CPU_USAGE) {
1304 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 ServiceManager.addService("permission", new PermissionController(m));
1307
1308 ApplicationInfo info =
1309 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001310 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001311 mSystemThread.installSystemApplicationInfo(info);
1312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 synchronized (mSelf) {
1314 ProcessRecord app = mSelf.newProcessRecordLocked(
1315 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001316 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001318 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001319 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001320 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 synchronized (mSelf.mPidsSelfLocked) {
1322 mSelf.mPidsSelfLocked.put(app.pid, app);
1323 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001324 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 }
1326 } catch (PackageManager.NameNotFoundException e) {
1327 throw new RuntimeException(
1328 "Unable to find android system package", e);
1329 }
1330 }
1331
1332 public void setWindowManager(WindowManagerService wm) {
1333 mWindowManager = wm;
1334 }
1335
1336 public static final Context main(int factoryTest) {
1337 AThread thr = new AThread();
1338 thr.start();
1339
1340 synchronized (thr) {
1341 while (thr.mService == null) {
1342 try {
1343 thr.wait();
1344 } catch (InterruptedException e) {
1345 }
1346 }
1347 }
1348
1349 ActivityManagerService m = thr.mService;
1350 mSelf = m;
1351 ActivityThread at = ActivityThread.systemMain();
1352 mSystemThread = at;
1353 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001354 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 m.mContext = context;
1356 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001357 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358
1359 m.mBatteryStatsService.publish(context);
1360 m.mUsageStatsService.publish(context);
1361
1362 synchronized (thr) {
1363 thr.mReady = true;
1364 thr.notifyAll();
1365 }
1366
1367 m.startRunning(null, null, null, null);
1368
1369 return context;
1370 }
1371
1372 public static ActivityManagerService self() {
1373 return mSelf;
1374 }
1375
1376 static class AThread extends Thread {
1377 ActivityManagerService mService;
1378 boolean mReady = false;
1379
1380 public AThread() {
1381 super("ActivityManager");
1382 }
1383
1384 public void run() {
1385 Looper.prepare();
1386
1387 android.os.Process.setThreadPriority(
1388 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001389 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390
1391 ActivityManagerService m = new ActivityManagerService();
1392
1393 synchronized (this) {
1394 mService = m;
1395 notifyAll();
1396 }
1397
1398 synchronized (this) {
1399 while (!mReady) {
1400 try {
1401 wait();
1402 } catch (InterruptedException e) {
1403 }
1404 }
1405 }
1406
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001407 // For debug builds, log event loop stalls to dropbox for analysis.
1408 if (StrictMode.conditionallyEnableDebugLogging()) {
1409 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1410 }
1411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 Looper.loop();
1413 }
1414 }
1415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 static class MemBinder extends Binder {
1417 ActivityManagerService mActivityManagerService;
1418 MemBinder(ActivityManagerService activityManagerService) {
1419 mActivityManagerService = activityManagerService;
1420 }
1421
1422 @Override
1423 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001424 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1425 != PackageManager.PERMISSION_GRANTED) {
1426 pw.println("Permission Denial: can't dump meminfo from from pid="
1427 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1428 + " without permission " + android.Manifest.permission.DUMP);
1429 return;
1430 }
1431
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001432 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001433 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 }
1435 }
1436
Chet Haase9c1e23b2011-03-24 10:51:31 -07001437 static class GraphicsBinder extends Binder {
1438 ActivityManagerService mActivityManagerService;
1439 GraphicsBinder(ActivityManagerService activityManagerService) {
1440 mActivityManagerService = activityManagerService;
1441 }
1442
1443 @Override
1444 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001445 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1446 != PackageManager.PERMISSION_GRANTED) {
1447 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1448 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1449 + " without permission " + android.Manifest.permission.DUMP);
1450 return;
1451 }
1452
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001453 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001454 }
1455 }
1456
Jeff Brown6754ba22011-12-14 20:20:01 -08001457 static class DbBinder extends Binder {
1458 ActivityManagerService mActivityManagerService;
1459 DbBinder(ActivityManagerService activityManagerService) {
1460 mActivityManagerService = activityManagerService;
1461 }
1462
1463 @Override
1464 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1465 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1466 != PackageManager.PERMISSION_GRANTED) {
1467 pw.println("Permission Denial: can't dump dbinfo from from pid="
1468 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1469 + " without permission " + android.Manifest.permission.DUMP);
1470 return;
1471 }
1472
1473 mActivityManagerService.dumpDbInfo(fd, pw, args);
1474 }
1475 }
1476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 static class CpuBinder extends Binder {
1478 ActivityManagerService mActivityManagerService;
1479 CpuBinder(ActivityManagerService activityManagerService) {
1480 mActivityManagerService = activityManagerService;
1481 }
1482
1483 @Override
1484 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001485 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1486 != PackageManager.PERMISSION_GRANTED) {
1487 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1488 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1489 + " without permission " + android.Manifest.permission.DUMP);
1490 return;
1491 }
1492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001494 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1495 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1496 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 }
1498 }
1499 }
1500
1501 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001502 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001503
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001504 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1505 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1506 mBroadcastQueues[0] = mFgBroadcastQueue;
1507 mBroadcastQueues[1] = mBgBroadcastQueue;
1508
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001509 mServices = new ActiveServices(this);
1510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 File dataDir = Environment.getDataDirectory();
1512 File systemDir = new File(dataDir, "system");
1513 systemDir.mkdirs();
1514 mBatteryStatsService = new BatteryStatsService(new File(
1515 systemDir, "batterystats.bin").toString());
1516 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001517 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001518 mOnBattery = DEBUG_POWER ? true
1519 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001520 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001522 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001523 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001524 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001526 // User 0 is the first and only user that runs at boot.
1527 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
1528
Jack Palevichb90d28c2009-07-22 15:35:24 -07001529 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1530 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1531
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001532 mConfiguration.setToDefaults();
1533 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001534 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 mProcessStats.init();
1536
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001537 mCompatModePackages = new CompatModePackages(this, systemDir);
1538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 // Add ourself to the Watchdog monitors.
1540 Watchdog.getInstance().addMonitor(this);
1541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 mProcessStatsThread = new Thread("ProcessStats") {
1543 public void run() {
1544 while (true) {
1545 try {
1546 try {
1547 synchronized(this) {
1548 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001549 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001551 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 // + ", write delay=" + nextWriteDelay);
1553 if (nextWriteDelay < nextCpuDelay) {
1554 nextCpuDelay = nextWriteDelay;
1555 }
1556 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001557 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 this.wait(nextCpuDelay);
1559 }
1560 }
1561 } catch (InterruptedException e) {
1562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 updateCpuStatsNow();
1564 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001565 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 }
1567 }
1568 }
1569 };
1570 mProcessStatsThread.start();
1571 }
1572
1573 @Override
1574 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1575 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001576 if (code == SYSPROPS_TRANSACTION) {
1577 // We need to tell all apps about the system property change.
1578 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1579 synchronized(this) {
1580 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1581 final int NA = apps.size();
1582 for (int ia=0; ia<NA; ia++) {
1583 ProcessRecord app = apps.valueAt(ia);
1584 if (app.thread != null) {
1585 procs.add(app.thread.asBinder());
1586 }
1587 }
1588 }
1589 }
1590
1591 int N = procs.size();
1592 for (int i=0; i<N; i++) {
1593 Parcel data2 = Parcel.obtain();
1594 try {
1595 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1596 } catch (RemoteException e) {
1597 }
1598 data2.recycle();
1599 }
1600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 try {
1602 return super.onTransact(code, data, reply, flags);
1603 } catch (RuntimeException e) {
1604 // The activity manager only throws security exceptions, so let's
1605 // log all others.
1606 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001607 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 }
1609 throw e;
1610 }
1611 }
1612
1613 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001614 final long now = SystemClock.uptimeMillis();
1615 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1616 return;
1617 }
1618 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1619 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 mProcessStatsThread.notify();
1621 }
1622 }
1623 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 void updateCpuStatsNow() {
1626 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001627 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 final long now = SystemClock.uptimeMillis();
1629 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001632 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1633 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 haveNewCpuStats = true;
1635 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001636 //Slog.i(TAG, mProcessStats.printCurrentState());
1637 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 // + mProcessStats.getTotalCpuPercent() + "%");
1639
Joe Onorato8a9b2202010-02-26 18:56:32 -08001640 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 if ("true".equals(SystemProperties.get("events.cpu"))) {
1642 int user = mProcessStats.getLastUserTime();
1643 int system = mProcessStats.getLastSystemTime();
1644 int iowait = mProcessStats.getLastIoWaitTime();
1645 int irq = mProcessStats.getLastIrqTime();
1646 int softIrq = mProcessStats.getLastSoftIrqTime();
1647 int idle = mProcessStats.getLastIdleTime();
1648
1649 int total = user + system + iowait + irq + softIrq + idle;
1650 if (total == 0) total = 1;
1651
Doug Zongker2bec3d42009-12-04 12:52:44 -08001652 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 ((user+system+iowait+irq+softIrq) * 100) / total,
1654 (user * 100) / total,
1655 (system * 100) / total,
1656 (iowait * 100) / total,
1657 (irq * 100) / total,
1658 (softIrq * 100) / total);
1659 }
1660 }
1661
Amith Yamasanie43530a2009-08-21 13:11:37 -07001662 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001663 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001664 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 synchronized(mPidsSelfLocked) {
1666 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001667 if (mOnBattery) {
1668 int perc = bstats.startAddingCpuLocked();
1669 int totalUTime = 0;
1670 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001671 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001673 ProcessStats.Stats st = mProcessStats.getStats(i);
1674 if (!st.working) {
1675 continue;
1676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001678 int otherUTime = (st.rel_utime*perc)/100;
1679 int otherSTime = (st.rel_stime*perc)/100;
1680 totalUTime += otherUTime;
1681 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 if (pr != null) {
1683 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001684 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1685 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001686 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001687 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001688 } else {
1689 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001690 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001691 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001692 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1693 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001694 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 }
1697 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001698 bstats.finishAddingCpuLocked(perc, totalUTime,
1699 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 }
1701 }
1702 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1705 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001706 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 }
1708 }
1709 }
1710 }
1711
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001712 @Override
1713 public void batteryNeedsCpuUpdate() {
1714 updateCpuStatsNow();
1715 }
1716
1717 @Override
1718 public void batteryPowerChanged(boolean onBattery) {
1719 // When plugging in, update the CPU stats first before changing
1720 // the plug state.
1721 updateCpuStatsNow();
1722 synchronized (this) {
1723 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001724 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001725 }
1726 }
1727 }
1728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 /**
1730 * Initialize the application bind args. These are passed to each
1731 * process when the bindApplication() IPC is sent to the process. They're
1732 * lazily setup to make sure the services are running when they're asked for.
1733 */
1734 private HashMap<String, IBinder> getCommonServicesLocked() {
1735 if (mAppBindArgs == null) {
1736 mAppBindArgs = new HashMap<String, IBinder>();
1737
1738 // Setup the application init args
1739 mAppBindArgs.put("package", ServiceManager.getService("package"));
1740 mAppBindArgs.put("window", ServiceManager.getService("window"));
1741 mAppBindArgs.put(Context.ALARM_SERVICE,
1742 ServiceManager.getService(Context.ALARM_SERVICE));
1743 }
1744 return mAppBindArgs;
1745 }
1746
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001747 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 if (mFocusedActivity != r) {
1749 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001750 if (r != null) {
1751 mWindowManager.setFocusedApp(r.appToken, true);
1752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 }
1754 }
1755
Dianne Hackborn906497c2010-05-10 15:57:38 -07001756 private final void updateLruProcessInternalLocked(ProcessRecord app,
1757 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001759 int lrui = mLruProcesses.indexOf(app);
1760 if (lrui >= 0) mLruProcesses.remove(lrui);
1761
1762 int i = mLruProcesses.size()-1;
1763 int skipTop = 0;
1764
Dianne Hackborn906497c2010-05-10 15:57:38 -07001765 app.lruSeq = mLruSeq;
1766
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001767 // compute the new weight for this process.
1768 if (updateActivityTime) {
1769 app.lastActivityTime = SystemClock.uptimeMillis();
1770 }
1771 if (app.activities.size() > 0) {
1772 // If this process has activities, we more strongly want to keep
1773 // it around.
1774 app.lruWeight = app.lastActivityTime;
1775 } else if (app.pubProviders.size() > 0) {
1776 // If this process contains content providers, we want to keep
1777 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001778 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001779 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001780 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001781 } else {
1782 // If this process doesn't have activities, we less strongly
1783 // want to keep it around, and generally want to avoid getting
1784 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001785 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001786 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001787 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001788 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001789
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001790 while (i >= 0) {
1791 ProcessRecord p = mLruProcesses.get(i);
1792 // If this app shouldn't be in front of the first N background
1793 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001794 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001795 skipTop--;
1796 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001797 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001798 mLruProcesses.add(i+1, app);
1799 break;
1800 }
1801 i--;
1802 }
1803 if (i < 0) {
1804 mLruProcesses.add(0, app);
1805 }
1806
Dianne Hackborn906497c2010-05-10 15:57:38 -07001807 // If the app is currently using a content provider or service,
1808 // bump those processes as well.
1809 if (app.connections.size() > 0) {
1810 for (ConnectionRecord cr : app.connections) {
1811 if (cr.binding != null && cr.binding.service != null
1812 && cr.binding.service.app != null
1813 && cr.binding.service.app.lruSeq != mLruSeq) {
Björn Davidsson90f9e312010-11-18 08:26:27 +01001814 updateLruProcessInternalLocked(cr.binding.service.app, false,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001815 updateActivityTime, i+1);
1816 }
1817 }
1818 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001819 for (int j=app.conProviders.size()-1; j>=0; j--) {
1820 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1821 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Jean-Baptiste Querub8c64052012-06-11 11:01:19 -07001822 updateLruProcessInternalLocked(cpr.proc, false,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001823 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001824 }
1825 }
1826
Joe Onorato8a9b2202010-02-26 18:56:32 -08001827 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 if (oomAdj) {
1829 updateOomAdjLocked();
1830 }
1831 }
1832
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001833 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001834 boolean oomAdj, boolean updateActivityTime) {
1835 mLruSeq++;
1836 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1837 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001838
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001839 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001841 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001842 // The system gets to run in any process. If there are multiple
1843 // processes with the same uid, just pick the first (this
1844 // should never happen).
1845 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1846 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001847 if (procs == null) return null;
1848 final int N = procs.size();
1849 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001850 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 }
1853 ProcessRecord proc = mProcessNames.get(processName, uid);
1854 return proc;
1855 }
1856
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001857 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001858 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001859 try {
1860 if (pm.performDexOpt(packageName)) {
1861 mDidDexOpt = true;
1862 }
1863 } catch (RemoteException e) {
1864 }
1865 }
1866
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001867 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 int transit = mWindowManager.getPendingAppTransition();
1869 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1870 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1871 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1872 }
1873
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001874 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001876 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1877 boolean isolated) {
1878 ProcessRecord app;
1879 if (!isolated) {
1880 app = getProcessRecordLocked(processName, info.uid);
1881 } else {
1882 // If this is an isolated process, it can't re-use an existing process.
1883 app = null;
1884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 // We don't have to do anything more if:
1886 // (1) There is an existing application record; and
1887 // (2) The caller doesn't think it is dead, OR there is no thread
1888 // object attached to it so we know it couldn't have crashed; and
1889 // (3) There is a pid assigned to it, so it is either starting or
1890 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001891 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 + " app=" + app + " knownToBeDead=" + knownToBeDead
1893 + " thread=" + (app != null ? app.thread : null)
1894 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001895 if (app != null && app.pid > 0) {
1896 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001897 // We already have the app running, or are waiting for it to
1898 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001899 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001900 // If this is a new package in the process, add the package to the list
1901 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001902 return app;
1903 } else {
1904 // An application record is attached to a previous process,
1905 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001906 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001907 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 String hostingNameStr = hostingName != null
1912 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001913
1914 if (!isolated) {
1915 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1916 // If we are in the background, then check to see if this process
1917 // is bad. If so, we will just silently fail.
1918 if (mBadProcesses.get(info.processName, info.uid) != null) {
1919 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1920 + "/" + info.processName);
1921 return null;
1922 }
1923 } else {
1924 // When the user is explicitly starting a process, then clear its
1925 // crash count so that we won't make it bad until they see at
1926 // least one crash dialog again, and make the process good again
1927 // if it had been bad.
1928 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001929 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001930 mProcessCrashTimes.remove(info.processName, info.uid);
1931 if (mBadProcesses.get(info.processName, info.uid) != null) {
1932 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1933 info.processName);
1934 mBadProcesses.remove(info.processName, info.uid);
1935 if (app != null) {
1936 app.bad = false;
1937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 }
1939 }
1940 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001943 app = newProcessRecordLocked(null, info, processName, isolated);
1944 if (app == null) {
1945 Slog.w(TAG, "Failed making new process record for "
1946 + processName + "/" + info.uid + " isolated=" + isolated);
1947 return null;
1948 }
1949 mProcessNames.put(processName, app.uid, app);
1950 if (isolated) {
1951 mIsolatedProcesses.put(app.uid, app);
1952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 } else {
1954 // If this is a new package in the process, add the package to the list
1955 app.addPackage(info.packageName);
1956 }
1957
1958 // If the system is not ready yet, then hold off on starting this
1959 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001960 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001961 && !isAllowedWhileBooting(info)
1962 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 if (!mProcessesOnHold.contains(app)) {
1964 mProcessesOnHold.add(app);
1965 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001966 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 return app;
1968 }
1969
1970 startProcessLocked(app, hostingType, hostingNameStr);
1971 return (app.pid != 0) ? app : null;
1972 }
1973
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001974 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1975 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1976 }
1977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 private final void startProcessLocked(ProcessRecord app,
1979 String hostingType, String hostingNameStr) {
1980 if (app.pid > 0 && app.pid != MY_PID) {
1981 synchronized (mPidsSelfLocked) {
1982 mPidsSelfLocked.remove(app.pid);
1983 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1984 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001985 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 }
1987
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001988 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1989 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 mProcessesOnHold.remove(app);
1991
1992 updateCpuStats();
1993
1994 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1995 mProcDeaths[0] = 0;
1996
1997 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001998 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002001 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002002 if (!app.isolated) {
2003 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002004 final PackageManager pm = mContext.getPackageManager();
2005 gids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002006
2007 if (Environment.isExternalStorageEmulated()) {
2008 if (pm.checkPermission(
2009 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2010 app.info.packageName) == PERMISSION_GRANTED) {
2011 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2012 } else {
2013 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2014 }
2015 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002016 } catch (PackageManager.NameNotFoundException e) {
2017 Slog.w(TAG, "Unable to retrieve gids", e);
2018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 }
2020 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2021 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2022 && mTopComponent != null
2023 && app.processName.equals(mTopComponent.getPackageName())) {
2024 uid = 0;
2025 }
2026 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2027 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2028 uid = 0;
2029 }
2030 }
2031 int debugFlags = 0;
2032 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2033 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002034 // Also turn on CheckJNI for debuggable apps. It's quite
2035 // awkward to turn on otherwise.
2036 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002038 // Run the app in safe mode if its manifest requests so or the
2039 // system is booted in safe mode.
2040 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2041 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002042 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2045 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2046 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002047 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2048 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 if ("1".equals(SystemProperties.get("debug.assert"))) {
2051 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2052 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002053
2054 // Start the process. It will either succeed and return a result containing
2055 // the PID of the new process, or else throw a RuntimeException.
2056 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002057 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002058 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2061 synchronized (bs) {
2062 if (bs.isOnBattery()) {
2063 app.batteryStats.incStartsLocked();
2064 }
2065 }
2066
Jeff Brown3f9dd282011-07-08 20:02:19 -07002067 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 app.processName, hostingType,
2069 hostingNameStr != null ? hostingNameStr : "");
2070
2071 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002072 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 }
2074
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002075 StringBuilder buf = mStringBuilder;
2076 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 buf.append("Start proc ");
2078 buf.append(app.processName);
2079 buf.append(" for ");
2080 buf.append(hostingType);
2081 if (hostingNameStr != null) {
2082 buf.append(" ");
2083 buf.append(hostingNameStr);
2084 }
2085 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002086 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 buf.append(" uid=");
2088 buf.append(uid);
2089 buf.append(" gids={");
2090 if (gids != null) {
2091 for (int gi=0; gi<gids.length; gi++) {
2092 if (gi != 0) buf.append(", ");
2093 buf.append(gids[gi]);
2094
2095 }
2096 }
2097 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002098 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002099 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002100 app.usingWrapper = startResult.usingWrapper;
2101 app.removed = false;
2102 synchronized (mPidsSelfLocked) {
2103 this.mPidsSelfLocked.put(startResult.pid, app);
2104 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2105 msg.obj = app;
2106 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2107 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 }
2109 } catch (RuntimeException e) {
2110 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002111 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002112 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 }
2114 }
2115
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002116 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 if (resumed) {
2118 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2119 } else {
2120 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2121 }
2122 }
2123
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002124 boolean startHomeActivityLocked(int userId, UserStartedState startingUser) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002125 if (mHeadless) {
2126 // Added because none of the other calls to ensureBootCompleted seem to fire
2127 // when running headless.
2128 ensureBootCompleted();
2129 return false;
2130 }
2131
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002132 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2133 && mTopAction == null) {
2134 // We are running in factory test mode, but unable to find
2135 // the factory test app, so just sit around displaying the
2136 // error message and don't try to start anything.
2137 return false;
2138 }
2139 Intent intent = new Intent(
2140 mTopAction,
2141 mTopData != null ? Uri.parse(mTopData) : null);
2142 intent.setComponent(mTopComponent);
2143 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2144 intent.addCategory(Intent.CATEGORY_HOME);
2145 }
2146 ActivityInfo aInfo =
2147 intent.resolveActivityInfo(mContext.getPackageManager(),
2148 STOCK_PM_FLAGS);
2149 if (aInfo != null) {
2150 intent.setComponent(new ComponentName(
2151 aInfo.applicationInfo.packageName, aInfo.name));
2152 // Don't do this if the home app is currently being
2153 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002154 aInfo = new ActivityInfo(aInfo);
2155 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002156 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2157 aInfo.applicationInfo.uid);
2158 if (app == null || app.instrumentationClass == null) {
2159 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002160 mMainStack.startActivityLocked(null, intent, null, aInfo,
2161 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002162 }
2163 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002164 if (startingUser != null) {
2165 mMainStack.addStartingUserLocked(startingUser);
2166 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002167
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002168 return true;
2169 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002170
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002171 /**
2172 * Starts the "new version setup screen" if appropriate.
2173 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002174 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002175 // Only do this once per boot.
2176 if (mCheckedForSetup) {
2177 return;
2178 }
2179
2180 // We will show this screen if the current one is a different
2181 // version than the last one shown, and we are not running in
2182 // low-level factory test mode.
2183 final ContentResolver resolver = mContext.getContentResolver();
2184 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2185 Settings.Secure.getInt(resolver,
2186 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2187 mCheckedForSetup = true;
2188
2189 // See if we should be showing the platform update setup UI.
2190 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2191 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2192 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2193
2194 // We don't allow third party apps to replace this.
2195 ResolveInfo ri = null;
2196 for (int i=0; ris != null && i<ris.size(); i++) {
2197 if ((ris.get(i).activityInfo.applicationInfo.flags
2198 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2199 ri = ris.get(i);
2200 break;
2201 }
2202 }
2203
2204 if (ri != null) {
2205 String vers = ri.activityInfo.metaData != null
2206 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2207 : null;
2208 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2209 vers = ri.activityInfo.applicationInfo.metaData.getString(
2210 Intent.METADATA_SETUP_VERSION);
2211 }
2212 String lastVers = Settings.Secure.getString(
2213 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2214 if (vers != null && !vers.equals(lastVers)) {
2215 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2216 intent.setComponent(new ComponentName(
2217 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002218 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2219 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002220 }
2221 }
2222 }
2223 }
2224
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002225 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002226 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002227 }
2228
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002229 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002230 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002231 throw new SecurityException("Isolated process not allowed to call " + caller);
2232 }
2233 }
2234
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002235 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002236 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002237 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002238 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2239 }
2240 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002241
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002242 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002243 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2244 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002245 synchronized (this) {
2246 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2247 }
2248 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002249
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002250 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002251 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002252 synchronized (this) {
2253 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2254 }
2255 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002256
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002257 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002258 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2259 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002260 synchronized (this) {
2261 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002262 }
2263 }
2264
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002265 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002266 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002267 synchronized (this) {
2268 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2269 }
2270 }
2271
2272 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002273 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2274 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002275 synchronized (this) {
2276 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2277 }
2278 }
2279
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002280 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002281 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002282 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002285 private void dispatchProcessesChanged() {
2286 int N;
2287 synchronized (this) {
2288 N = mPendingProcessChanges.size();
2289 if (mActiveProcessChanges.length < N) {
2290 mActiveProcessChanges = new ProcessChangeItem[N];
2291 }
2292 mPendingProcessChanges.toArray(mActiveProcessChanges);
2293 mAvailProcessChanges.addAll(mPendingProcessChanges);
2294 mPendingProcessChanges.clear();
2295 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2296 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002297 int i = mProcessObservers.beginBroadcast();
2298 while (i > 0) {
2299 i--;
2300 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2301 if (observer != null) {
2302 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002303 for (int j=0; j<N; j++) {
2304 ProcessChangeItem item = mActiveProcessChanges[j];
2305 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2306 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2307 + item.pid + " uid=" + item.uid + ": "
2308 + item.foregroundActivities);
2309 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2310 item.foregroundActivities);
2311 }
2312 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2313 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2314 + item.pid + " uid=" + item.uid + ": " + item.importance);
2315 observer.onImportanceChanged(item.pid, item.uid,
2316 item.importance);
2317 }
2318 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002319 } catch (RemoteException e) {
2320 }
2321 }
2322 }
2323 mProcessObservers.finishBroadcast();
2324 }
2325
2326 private void dispatchProcessDied(int pid, int uid) {
2327 int i = mProcessObservers.beginBroadcast();
2328 while (i > 0) {
2329 i--;
2330 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2331 if (observer != null) {
2332 try {
2333 observer.onProcessDied(pid, uid);
2334 } catch (RemoteException e) {
2335 }
2336 }
2337 }
2338 mProcessObservers.finishBroadcast();
2339 }
2340
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002341 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002342 final int N = mPendingActivityLaunches.size();
2343 if (N <= 0) {
2344 return;
2345 }
2346 for (int i=0; i<N; i++) {
2347 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002348 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002349 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002350 }
2351 mPendingActivityLaunches.clear();
2352 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002353
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002354 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002355 Intent intent, String resolvedType, IBinder resultTo,
2356 String resultWho, int requestCode, int startFlags,
2357 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002358 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002359 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002360 }
2361
2362 public final int startActivityAsUser(IApplicationThread caller,
2363 Intent intent, String resolvedType, IBinder resultTo,
2364 String resultWho, int requestCode, int startFlags,
2365 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002366 enforceNotIsolatedCaller("startActivity");
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002367 if (userId != UserHandle.getCallingUserId()) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002368 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2369 false, true, "startActivity", null);
Amith Yamasani82644082012-08-03 13:09:11 -07002370 } else {
2371 if (intent.getCategories() != null
2372 && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2373 // Requesting home, set the identity to the current user
2374 // HACK!
2375 userId = mCurrentUserId;
Amith Yamasani742a6712011-05-04 14:49:28 -07002376 }
2377 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002378 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002379 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2380 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002381 }
2382
2383 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002384 Intent intent, String resolvedType, IBinder resultTo,
2385 String resultWho, int requestCode, int startFlags, String profileFile,
2386 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002387 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002388 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002389 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002390 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002391 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002392 return res;
2393 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002394
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002395 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002396 Intent intent, String resolvedType, IBinder resultTo,
2397 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002398 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002399 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn41203752012-08-31 14:05:51 -07002400 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2401 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002402 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002403 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002404 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002405 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002406 }
2407
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002408 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002409 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002410 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002411 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002412 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002413 // Refuse possible leaked file descriptors
2414 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2415 throw new IllegalArgumentException("File descriptors passed in Intent");
2416 }
2417
2418 IIntentSender sender = intent.getTarget();
2419 if (!(sender instanceof PendingIntentRecord)) {
2420 throw new IllegalArgumentException("Bad PendingIntent object");
2421 }
2422
2423 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002424
2425 synchronized (this) {
2426 // If this is coming from the currently resumed activity, it is
2427 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002428 if (mMainStack.mResumedActivity != null
2429 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002430 Binder.getCallingUid()) {
2431 mAppSwitchesAllowedTime = 0;
2432 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002433 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002434 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2435 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002436 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002437 }
2438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002440 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 // Refuse possible leaked file descriptors
2442 if (intent != null && intent.hasFileDescriptors() == true) {
2443 throw new IllegalArgumentException("File descriptors passed in Intent");
2444 }
2445
2446 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002447 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2448 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002449 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 return false;
2451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 if (r.app == null || r.app.thread == null) {
2453 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002454 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 return false;
2456 }
2457 intent = new Intent(intent);
2458 // The caller is not allowed to change the data.
2459 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2460 // And we are resetting to find the next component...
2461 intent.setComponent(null);
2462
2463 ActivityInfo aInfo = null;
2464 try {
2465 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002466 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002468 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002469 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470
2471 // Look for the original activity in the list...
2472 final int N = resolves != null ? resolves.size() : 0;
2473 for (int i=0; i<N; i++) {
2474 ResolveInfo rInfo = resolves.get(i);
2475 if (rInfo.activityInfo.packageName.equals(r.packageName)
2476 && rInfo.activityInfo.name.equals(r.info.name)) {
2477 // We found the current one... the next matching is
2478 // after it.
2479 i++;
2480 if (i<N) {
2481 aInfo = resolves.get(i).activityInfo;
2482 }
2483 break;
2484 }
2485 }
2486 } catch (RemoteException e) {
2487 }
2488
2489 if (aInfo == null) {
2490 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002491 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 return false;
2493 }
2494
2495 intent.setComponent(new ComponentName(
2496 aInfo.applicationInfo.packageName, aInfo.name));
2497 intent.setFlags(intent.getFlags()&~(
2498 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2499 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2500 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2501 Intent.FLAG_ACTIVITY_NEW_TASK));
2502
2503 // Okay now we need to start the new activity, replacing the
2504 // currently running activity. This is a little tricky because
2505 // we want to start the new one as if the current one is finished,
2506 // but not finish the current one first so that there is no flicker.
2507 // And thus...
2508 final boolean wasFinishing = r.finishing;
2509 r.finishing = true;
2510
2511 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002512 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 final String resultWho = r.resultWho;
2514 final int requestCode = r.requestCode;
2515 r.resultTo = null;
2516 if (resultTo != null) {
2517 resultTo.removeResultsLocked(r, resultWho, requestCode);
2518 }
2519
2520 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002521 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002522 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2523 resultWho, requestCode, -1, r.launchedFromUid, 0,
2524 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 Binder.restoreCallingIdentity(origId);
2526
2527 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002528 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 return false;
2530 }
2531 return true;
2532 }
2533 }
2534
Dianne Hackborn41203752012-08-31 14:05:51 -07002535 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002537 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2538
2539 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2540 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541
Amith Yamasani742a6712011-05-04 14:49:28 -07002542 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002543 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002544 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002545 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002546 }
2547
2548 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002549 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002550 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002551 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002552 options, UserHandle.getCallingUserId());
Amith Yamasani742a6712011-05-04 14:49:28 -07002553 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002554 }
2555
Dianne Hackborn41203752012-08-31 14:05:51 -07002556 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002557 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002558 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002559
Dianne Hackborn41203752012-08-31 14:05:51 -07002560 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2561 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002562 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002563 options, userId);
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
Dianne Hackborn41203752012-08-31 14:05:51 -07002697 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2698 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002699 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002700 }
2701 }
2702
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002703 public void crashApplication(int uid, int initialPid, String packageName,
2704 String message) {
2705 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2706 != PackageManager.PERMISSION_GRANTED) {
2707 String msg = "Permission Denial: crashApplication() from pid="
2708 + Binder.getCallingPid()
2709 + ", uid=" + Binder.getCallingUid()
2710 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2711 Slog.w(TAG, msg);
2712 throw new SecurityException(msg);
2713 }
2714
2715 synchronized(this) {
2716 ProcessRecord proc = null;
2717
2718 // Figure out which process to kill. We don't trust that initialPid
2719 // still has any relation to current pids, so must scan through the
2720 // list.
2721 synchronized (mPidsSelfLocked) {
2722 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2723 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002724 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002725 continue;
2726 }
2727 if (p.pid == initialPid) {
2728 proc = p;
2729 break;
2730 }
2731 for (String str : p.pkgList) {
2732 if (str.equals(packageName)) {
2733 proc = p;
2734 }
2735 }
2736 }
2737 }
2738
2739 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002740 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002741 + " initialPid=" + initialPid
2742 + " packageName=" + packageName);
2743 return;
2744 }
2745
2746 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002747 if (proc.pid == Process.myPid()) {
2748 Log.w(TAG, "crashApplication: trying to crash self!");
2749 return;
2750 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002751 long ident = Binder.clearCallingIdentity();
2752 try {
2753 proc.thread.scheduleCrash(message);
2754 } catch (RemoteException e) {
2755 }
2756 Binder.restoreCallingIdentity(ident);
2757 }
2758 }
2759 }
2760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 public final void finishSubActivity(IBinder token, String resultWho,
2762 int requestCode) {
2763 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002765 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 Binder.restoreCallingIdentity(origId);
2767 }
2768 }
2769
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002770 public boolean finishActivityAffinity(IBinder token) {
2771 synchronized(this) {
2772 final long origId = Binder.clearCallingIdentity();
2773 boolean res = mMainStack.finishActivityAffinityLocked(token);
2774 Binder.restoreCallingIdentity(origId);
2775 return res;
2776 }
2777 }
2778
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002779 public boolean willActivityBeVisible(IBinder token) {
2780 synchronized(this) {
2781 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002782 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2783 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002784 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002785 return true;
2786 }
2787 if (r.fullscreen && !r.finishing) {
2788 return false;
2789 }
2790 }
2791 return true;
2792 }
2793 }
2794
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002795 public void overridePendingTransition(IBinder token, String packageName,
2796 int enterAnim, int exitAnim) {
2797 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002798 ActivityRecord self = mMainStack.isInStackLocked(token);
2799 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002800 return;
2801 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002802
2803 final long origId = Binder.clearCallingIdentity();
2804
2805 if (self.state == ActivityState.RESUMED
2806 || self.state == ActivityState.PAUSING) {
2807 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002808 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002809 }
2810
2811 Binder.restoreCallingIdentity(origId);
2812 }
2813 }
2814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 * Main function for removing an existing process from the activity manager
2817 * as a result of that process going away. Clears out all connections
2818 * to the process.
2819 */
2820 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002821 boolean restarting, boolean allowRestart) {
2822 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002824 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 }
2826
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002827 if (mProfileProc == app) {
2828 clearProfilerLocked();
2829 }
2830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002832 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2833 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2834 mMainStack.mPausingActivity = null;
2835 }
2836 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2837 mMainStack.mLastPausedActivity = null;
2838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839
2840 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002841 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842
2843 boolean atTop = true;
2844 boolean hasVisibleActivities = false;
2845
2846 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002847 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002848 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849 TAG, "Removing app " + app + " from history with " + i + " entries");
2850 while (i > 0) {
2851 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002852 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002853 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2855 if (r.app == app) {
2856 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002857 if (ActivityStack.DEBUG_ADD_REMOVE) {
2858 RuntimeException here = new RuntimeException("here");
2859 here.fillInStackTrace();
2860 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2861 + ": haveState=" + r.haveState
2862 + " stateNotNeeded=" + r.stateNotNeeded
2863 + " finishing=" + r.finishing
2864 + " state=" + r.state, here);
2865 }
2866 if (!r.finishing) {
2867 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002868 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2869 System.identityHashCode(r),
2870 r.task.taskId, r.shortComponentName,
2871 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002872 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002873 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874
2875 } else {
2876 // We have the current state for this activity, so
2877 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002878 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 TAG, "Keeping entry, setting app to null");
2880 if (r.visible) {
2881 hasVisibleActivities = true;
2882 }
2883 r.app = null;
2884 r.nowVisible = false;
2885 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002886 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2887 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 r.icicle = null;
2889 }
2890 }
2891
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002892 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 }
2894 atTop = false;
2895 }
2896
2897 app.activities.clear();
2898
2899 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002900 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 + " running instrumentation " + app.instrumentationClass);
2902 Bundle info = new Bundle();
2903 info.putString("shortMsg", "Process crashed.");
2904 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2905 }
2906
2907 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002908 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 // If there was nothing to resume, and we are not already
2910 // restarting this process, but there is a visible activity that
2911 // is hosted by the process... then make sure all visible
2912 // activities are running, taking care of restarting this
2913 // process.
2914 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002915 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 }
2917 }
2918 }
2919 }
2920
2921 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2922 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002924 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2925 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2927 return i;
2928 }
2929 }
2930 return -1;
2931 }
2932
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002933 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 IApplicationThread thread) {
2935 if (thread == null) {
2936 return null;
2937 }
2938
2939 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002940 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 }
2942
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002943 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 IApplicationThread thread) {
2945
2946 mProcDeaths[0]++;
2947
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002948 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2949 synchronized (stats) {
2950 stats.noteProcessDiedLocked(app.info.uid, pid);
2951 }
2952
Magnus Edlund7bb25812010-02-24 15:45:06 +01002953 // Clean up already done if the process has been re-started.
2954 if (app.pid == pid && app.thread != null &&
2955 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002956 if (!app.killedBackground) {
2957 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2958 + ") has died.");
2959 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002960 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002961 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 TAG, "Dying app: " + app + ", pid: " + pid
2963 + ", thread: " + thread.asBinder());
2964 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002965 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966
2967 if (doLowMem) {
2968 // If there are no longer any background processes running,
2969 // and the app that died was not running instrumentation,
2970 // then tell everyone we are now low on memory.
2971 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002972 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2973 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002974 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 haveBg = true;
2976 break;
2977 }
2978 }
2979
2980 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002981 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002982 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002983 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2984 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002985 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002986 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2987 // The low memory report is overriding any current
2988 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002989 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002990 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002991 rec.lastRequestedGc = 0;
2992 } else {
2993 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002995 rec.reportLowMemory = true;
2996 rec.lastLowMemory = now;
2997 mProcessesToGc.remove(rec);
2998 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 }
3000 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003001 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003002 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 }
3004 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003005 } else if (app.pid != pid) {
3006 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003007 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003008 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003009 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003010 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003011 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 + thread.asBinder());
3013 }
3014 }
3015
Dan Egnor42471dd2010-01-07 17:25:22 -08003016 /**
3017 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003018 * @param clearTraces causes the dump file to be erased prior to the new
3019 * traces being written, if true; when false, the new traces will be
3020 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003021 * @param firstPids of dalvik VM processes to dump stack traces for first
3022 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003023 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003024 * @return file containing stack traces, or null if no dump file is configured
3025 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003026 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003027 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003028 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3029 if (tracesPath == null || tracesPath.length() == 0) {
3030 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003032
3033 File tracesFile = new File(tracesPath);
3034 try {
3035 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003036 if (!tracesDir.exists()) {
3037 tracesFile.mkdirs();
3038 if (!SELinux.restorecon(tracesDir)) {
3039 return null;
3040 }
3041 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003042 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3043
Christopher Tate6ee412d2010-05-28 12:01:56 -07003044 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003045 tracesFile.createNewFile();
3046 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3047 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003048 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003049 return null;
3050 }
3051
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003052 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003053 return tracesFile;
3054 }
3055
3056 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003057 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003058 // Use a FileObserver to detect when traces finish writing.
3059 // The order of traces is considered important to maintain for legibility.
3060 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3061 public synchronized void onEvent(int event, String path) { notify(); }
3062 };
3063
3064 try {
3065 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003066
3067 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003068 if (firstPids != null) {
3069 try {
3070 int num = firstPids.size();
3071 for (int i = 0; i < num; i++) {
3072 synchronized (observer) {
3073 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3074 observer.wait(200); // Wait for write-close, give up after 200msec
3075 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003076 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003077 } catch (InterruptedException e) {
3078 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003079 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003080 }
3081
3082 // Next measure CPU usage.
3083 if (processStats != null) {
3084 processStats.init();
3085 System.gc();
3086 processStats.update();
3087 try {
3088 synchronized (processStats) {
3089 processStats.wait(500); // measure over 1/2 second.
3090 }
3091 } catch (InterruptedException e) {
3092 }
3093 processStats.update();
3094
3095 // We'll take the stack crawls of just the top apps using CPU.
3096 final int N = processStats.countWorkingStats();
3097 int numProcs = 0;
3098 for (int i=0; i<N && numProcs<5; i++) {
3099 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3100 if (lastPids.indexOfKey(stats.pid) >= 0) {
3101 numProcs++;
3102 try {
3103 synchronized (observer) {
3104 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3105 observer.wait(200); // Wait for write-close, give up after 200msec
3106 }
3107 } catch (InterruptedException e) {
3108 Log.wtf(TAG, e);
3109 }
3110
3111 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003112 }
3113 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003114
Dan Egnor42471dd2010-01-07 17:25:22 -08003115 } finally {
3116 observer.stopWatching();
3117 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003118
3119 if (nativeProcs != null) {
3120 int[] pids = Process.getPidsForCommands(nativeProcs);
3121 if (pids != null) {
3122 for (int pid : pids) {
3123 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3124 }
3125 }
3126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 }
3128
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003129 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003130 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003131 return;
3132 }
3133 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3134 if (tracesPath == null || tracesPath.length() == 0) {
3135 return;
3136 }
3137
3138 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3139 StrictMode.allowThreadDiskWrites();
3140 try {
3141 final File tracesFile = new File(tracesPath);
3142 final File tracesDir = tracesFile.getParentFile();
3143 final File tracesTmp = new File(tracesDir, "__tmp__");
3144 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003145 if (!tracesDir.exists()) {
3146 tracesFile.mkdirs();
3147 if (!SELinux.restorecon(tracesDir.getPath())) {
3148 return;
3149 }
3150 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003151 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3152
3153 if (tracesFile.exists()) {
3154 tracesTmp.delete();
3155 tracesFile.renameTo(tracesTmp);
3156 }
3157 StringBuilder sb = new StringBuilder();
3158 Time tobj = new Time();
3159 tobj.set(System.currentTimeMillis());
3160 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3161 sb.append(": ");
3162 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3163 sb.append(" since ");
3164 sb.append(msg);
3165 FileOutputStream fos = new FileOutputStream(tracesFile);
3166 fos.write(sb.toString().getBytes());
3167 if (app == null) {
3168 fos.write("\n*** No application process!".getBytes());
3169 }
3170 fos.close();
3171 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3172 } catch (IOException e) {
3173 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3174 return;
3175 }
3176
3177 if (app != null) {
3178 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3179 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003180 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003181 }
3182
3183 File lastTracesFile = null;
3184 File curTracesFile = null;
3185 for (int i=9; i>=0; i--) {
3186 String name = String.format("slow%02d.txt", i);
3187 curTracesFile = new File(tracesDir, name);
3188 if (curTracesFile.exists()) {
3189 if (lastTracesFile != null) {
3190 curTracesFile.renameTo(lastTracesFile);
3191 } else {
3192 curTracesFile.delete();
3193 }
3194 }
3195 lastTracesFile = curTracesFile;
3196 }
3197 tracesFile.renameTo(curTracesFile);
3198 if (tracesTmp.exists()) {
3199 tracesTmp.renameTo(tracesFile);
3200 }
3201 } finally {
3202 StrictMode.setThreadPolicy(oldPolicy);
3203 }
3204 }
3205
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003206 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3207 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003208 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3209 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3210
Dianne Hackborn287952c2010-09-22 22:34:31 -07003211 if (mController != null) {
3212 try {
3213 // 0 == continue, -1 = kill process immediately
3214 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3215 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3216 } catch (RemoteException e) {
3217 mController = null;
3218 }
3219 }
3220
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003221 long anrTime = SystemClock.uptimeMillis();
3222 if (MONITOR_CPU_USAGE) {
3223 updateCpuStatsNow();
3224 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003225
3226 synchronized (this) {
3227 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3228 if (mShuttingDown) {
3229 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3230 return;
3231 } else if (app.notResponding) {
3232 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3233 return;
3234 } else if (app.crashing) {
3235 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3236 return;
3237 }
3238
3239 // In case we come through here for the same app before completing
3240 // this one, mark as anring now so we will bail out.
3241 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003242
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003243 // Log the ANR to the event log.
3244 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3245 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003246
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003247 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003248 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003249
3250 int parentPid = app.pid;
3251 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003252 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003253
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003254 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003255
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003256 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3257 ProcessRecord r = mLruProcesses.get(i);
3258 if (r != null && r.thread != null) {
3259 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003260 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3261 if (r.persistent) {
3262 firstPids.add(pid);
3263 } else {
3264 lastPids.put(pid, Boolean.TRUE);
3265 }
3266 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 }
3269 }
3270
Dan Egnor42471dd2010-01-07 17:25:22 -08003271 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003272 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003273 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003274 info.append("ANR in ").append(app.processName);
3275 if (activity != null && activity.shortComponentName != null) {
3276 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003277 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003278 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003280 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003282 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003283 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285
Dianne Hackborn287952c2010-09-22 22:34:31 -07003286 final ProcessStats processStats = new ProcessStats(true);
3287
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003288 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003289
Dan Egnor42471dd2010-01-07 17:25:22 -08003290 String cpuInfo = null;
3291 if (MONITOR_CPU_USAGE) {
3292 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003293 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003294 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003295 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003296 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003297 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 }
3299
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003300 info.append(processStats.printCurrentState(anrTime));
3301
Joe Onorato8a9b2202010-02-26 18:56:32 -08003302 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003303 if (tracesFile == null) {
3304 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3305 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3306 }
3307
Jeff Sharkeya353d262011-10-28 11:12:06 -07003308 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3309 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003310
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003311 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003313 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3314 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003316 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3317 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 }
3319 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003320 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 }
3322 }
3323
Dan Egnor42471dd2010-01-07 17:25:22 -08003324 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3325 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3326 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003327
3328 synchronized (this) {
3329 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003330 Slog.w(TAG, "Killing " + app + ": background ANR");
3331 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3332 app.processName, app.setAdj, "background ANR");
3333 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003334 return;
3335 }
3336
3337 // Set the app's notResponding state, and look up the errorReportReceiver
3338 makeAppNotRespondingLocked(app,
3339 activity != null ? activity.shortComponentName : null,
3340 annotation != null ? "ANR " + annotation : "ANR",
3341 info.toString());
3342
3343 // Bring up the infamous App Not Responding dialog
3344 Message msg = Message.obtain();
3345 HashMap map = new HashMap();
3346 msg.what = SHOW_NOT_RESPONDING_MSG;
3347 msg.obj = map;
3348 map.put("app", app);
3349 if (activity != null) {
3350 map.put("activity", activity);
3351 }
3352
3353 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 }
3356
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003357 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3358 if (!mLaunchWarningShown) {
3359 mLaunchWarningShown = true;
3360 mHandler.post(new Runnable() {
3361 @Override
3362 public void run() {
3363 synchronized (ActivityManagerService.this) {
3364 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3365 d.show();
3366 mHandler.postDelayed(new Runnable() {
3367 @Override
3368 public void run() {
3369 synchronized (ActivityManagerService.this) {
3370 d.dismiss();
3371 mLaunchWarningShown = false;
3372 }
3373 }
3374 }, 4000);
3375 }
3376 }
3377 });
3378 }
3379 }
3380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003382 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003383 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 int uid = Binder.getCallingUid();
3385 int pid = Binder.getCallingPid();
3386 long callingId = Binder.clearCallingIdentity();
3387 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003388 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 int pkgUid = -1;
3390 synchronized(this) {
3391 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003392 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 } catch (RemoteException e) {
3394 }
3395 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003396 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 return false;
3398 }
3399 if (uid == pkgUid || checkComponentPermission(
3400 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003401 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003403 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 } else {
3405 throw new SecurityException(pid+" does not have permission:"+
3406 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3407 "for process:"+packageName);
3408 }
3409 }
3410
3411 try {
3412 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003413 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3415 Uri.fromParts("package", packageName, null));
3416 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003417 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003418 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 } catch (RemoteException e) {
3420 }
3421 } finally {
3422 Binder.restoreCallingIdentity(callingId);
3423 }
3424 return true;
3425 }
3426
Dianne Hackborn03abb812010-01-04 18:43:19 -08003427 public void killBackgroundProcesses(final String packageName) {
3428 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3429 != PackageManager.PERMISSION_GRANTED &&
3430 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3431 != PackageManager.PERMISSION_GRANTED) {
3432 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 + Binder.getCallingPid()
3434 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003435 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003436 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 throw new SecurityException(msg);
3438 }
3439
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003440 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 long callingId = Binder.clearCallingIdentity();
3442 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003443 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 int pkgUid = -1;
3445 synchronized(this) {
3446 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003447 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 } catch (RemoteException e) {
3449 }
3450 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003451 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 return;
3453 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003454 killPackageProcessesLocked(packageName, pkgUid, -1,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003455 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3456 }
3457 } finally {
3458 Binder.restoreCallingIdentity(callingId);
3459 }
3460 }
3461
3462 public void killAllBackgroundProcesses() {
3463 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3464 != PackageManager.PERMISSION_GRANTED) {
3465 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3466 + Binder.getCallingPid()
3467 + ", uid=" + Binder.getCallingUid()
3468 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3469 Slog.w(TAG, msg);
3470 throw new SecurityException(msg);
3471 }
3472
3473 long callingId = Binder.clearCallingIdentity();
3474 try {
3475 synchronized(this) {
3476 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3477 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3478 final int NA = apps.size();
3479 for (int ia=0; ia<NA; ia++) {
3480 ProcessRecord app = apps.valueAt(ia);
3481 if (app.persistent) {
3482 // we don't kill persistent processes
3483 continue;
3484 }
3485 if (app.removed) {
3486 procs.add(app);
3487 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3488 app.removed = true;
3489 procs.add(app);
3490 }
3491 }
3492 }
3493
3494 int N = procs.size();
3495 for (int i=0; i<N; i++) {
3496 removeProcessLocked(procs.get(i), false, true, "kill all background");
3497 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003498 }
3499 } finally {
3500 Binder.restoreCallingIdentity(callingId);
3501 }
3502 }
3503
3504 public void forceStopPackage(final String packageName) {
3505 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3506 != PackageManager.PERMISSION_GRANTED) {
3507 String msg = "Permission Denial: forceStopPackage() from pid="
3508 + Binder.getCallingPid()
3509 + ", uid=" + Binder.getCallingUid()
3510 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003511 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003512 throw new SecurityException(msg);
3513 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003514 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003515 long callingId = Binder.clearCallingIdentity();
3516 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003517 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003518 int pkgUid = -1;
3519 synchronized(this) {
3520 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003521 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003522 } catch (RemoteException e) {
3523 }
3524 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003525 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003526 return;
3527 }
3528 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003529 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003530 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003531 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003532 } catch (IllegalArgumentException e) {
3533 Slog.w(TAG, "Failed trying to unstop package "
3534 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536 }
3537 } finally {
3538 Binder.restoreCallingIdentity(callingId);
3539 }
3540 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003541
3542 /*
3543 * The pkg name and uid have to be specified.
3544 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3545 */
3546 public void killApplicationWithUid(String pkg, int uid) {
3547 if (pkg == null) {
3548 return;
3549 }
3550 // Make sure the uid is valid.
3551 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003552 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003553 return;
3554 }
3555 int callerUid = Binder.getCallingUid();
3556 // Only the system server can kill an application
3557 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003558 // Post an aysnc message to kill the application
3559 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3560 msg.arg1 = uid;
3561 msg.arg2 = 0;
3562 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003563 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003564 } else {
3565 throw new SecurityException(callerUid + " cannot kill pkg: " +
3566 pkg);
3567 }
3568 }
3569
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003570 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003571 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003572
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003573 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003574 final int uid = Binder.getCallingUid();
3575 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003576 try {
3577 synchronized (this) {
3578 // Only allow this from foreground processes, so that background
3579 // applications can't abuse it to prevent system UI from being shown.
3580 if (uid >= Process.FIRST_APPLICATION_UID) {
3581 ProcessRecord proc;
3582 synchronized (mPidsSelfLocked) {
3583 proc = mPidsSelfLocked.get(pid);
3584 }
3585 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3586 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3587 + " from background process " + proc);
3588 return;
3589 }
3590 }
3591 closeSystemDialogsLocked(reason);
3592 }
3593 } finally {
3594 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003595 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003596 }
3597
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003598 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003599 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003600 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003601 if (reason != null) {
3602 intent.putExtra("reason", reason);
3603 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003604 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003605
Dianne Hackborne302a162012-05-15 14:58:32 -07003606 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3607 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003608 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003609 r.stack.finishActivityLocked(r, i,
3610 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003611 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003612 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003613
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003614 broadcastIntentLocked(null, null, intent, null,
3615 null, 0, null, null, null, false, false, -1,
3616 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003617 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003618
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003619 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003620 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003621 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003622 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3623 for (int i=pids.length-1; i>=0; i--) {
3624 infos[i] = new Debug.MemoryInfo();
3625 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003626 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003627 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003628 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003629
Dianne Hackbornb437e092011-08-05 17:50:29 -07003630 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003631 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003632 long[] pss = new long[pids.length];
3633 for (int i=pids.length-1; i>=0; i--) {
3634 pss[i] = Debug.getPss(pids[i]);
3635 }
3636 return pss;
3637 }
3638
Christopher Tate5e1ab332009-09-01 20:32:49 -07003639 public void killApplicationProcess(String processName, int uid) {
3640 if (processName == null) {
3641 return;
3642 }
3643
3644 int callerUid = Binder.getCallingUid();
3645 // Only the system server can kill an application
3646 if (callerUid == Process.SYSTEM_UID) {
3647 synchronized (this) {
3648 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003649 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003650 try {
3651 app.thread.scheduleSuicide();
3652 } catch (RemoteException e) {
3653 // If the other end already died, then our work here is done.
3654 }
3655 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003656 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003657 + processName + " / " + uid);
3658 }
3659 }
3660 } else {
3661 throw new SecurityException(callerUid + " cannot kill app process: " +
3662 processName);
3663 }
3664 }
3665
Dianne Hackborn03abb812010-01-04 18:43:19 -08003666 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003667 forceStopPackageLocked(packageName, uid, false, false, true, false,
3668 UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3670 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003671 if (!mProcessesReady) {
3672 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 intent.putExtra(Intent.EXTRA_UID, uid);
3675 broadcastIntentLocked(null, null, intent,
3676 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003677 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003678 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003680
3681 private void forceStopUserLocked(int userId) {
3682 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3683 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
3684 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3685 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3686 broadcastIntentLocked(null, null, intent,
3687 null, null, 0, null, null, null,
3688 false, false,
3689 MY_PID, Process.SYSTEM_UID, userId);
3690 }
3691
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003692 private final boolean killPackageProcessesLocked(String packageName, int uid,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003693 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3694 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003695 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696
Dianne Hackborn03abb812010-01-04 18:43:19 -08003697 // Remove all processes this package may have touched: all with the
3698 // same UID (except for the system or root user), and all whose name
3699 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003700 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003701 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3702 final int NA = apps.size();
3703 for (int ia=0; ia<NA; ia++) {
3704 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003705 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003706 // we don't kill persistent processes
3707 continue;
3708 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003709 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003710 if (doit) {
3711 procs.add(app);
3712 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003713 // If no package is specified, we call all processes under the
3714 // give user id.
3715 } else if (packageName == null) {
3716 if (app.userId == userId) {
3717 if (app.setAdj >= minOomAdj) {
3718 if (!doit) {
3719 return true;
3720 }
3721 app.removed = true;
3722 procs.add(app);
3723 }
3724 }
Amith Yamasani13593602012-03-22 16:16:17 -07003725 // If uid is specified and the uid and process name match
3726 // Or, the uid is not specified and the process name matches
3727 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003728 || ((app.processName.equals(packageName)
3729 || app.processName.startsWith(procNamePrefix))
3730 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003731 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003732 if (!doit) {
3733 return true;
3734 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003735 app.removed = true;
3736 procs.add(app);
3737 }
3738 }
3739 }
3740 }
3741
3742 int N = procs.size();
3743 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003744 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003745 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003746 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003747 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003748
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003749 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003750 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003751 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003752 int i;
3753 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003754
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003755 if (uid < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003757 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 } catch (RemoteException e) {
3759 }
3760 }
3761
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003762 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003763 if (name != null) {
3764 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
3765 } else {
3766 Slog.i(TAG, "Force stopping user " + userId);
3767 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003768
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003769 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3770 while (badApps.hasNext()) {
3771 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003772 for (i=ba.size()-1; i>=0; i--) {
3773 boolean remove = false;
3774 final int entUid = ba.keyAt(i);
3775 if (name != null) {
3776 if (entUid == uid) {
3777 remove = true;
3778 }
3779 } else if (UserHandle.getUserId(entUid) == userId) {
3780 remove = true;
3781 }
3782 if (remove) {
3783 ba.removeAt(i);
3784 }
3785 }
3786 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003787 badApps.remove();
3788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 }
3790 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003791
3792 boolean didSomething = killPackageProcessesLocked(name, uid,
3793 name == null ? userId : -1 , -100, callerWillRestart, false,
3794 doit, evenPersistent,
3795 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003797 TaskRecord lastTask = null;
3798 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003799 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003800 final boolean samePackage = r.packageName.equals(name)
3801 || (name == null && r.userId == userId);
Amith Yamasani13593602012-03-22 16:16:17 -07003802 if (r.userId == userId
3803 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003804 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003805 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003806 if (r.finishing) {
3807 // If this activity is just finishing, then it is not
3808 // interesting as far as something to stop.
3809 continue;
3810 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003811 return true;
3812 }
3813 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003814 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003815 if (samePackage) {
3816 if (r.app != null) {
3817 r.app.removed = true;
3818 }
3819 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003821 lastTask = r.task;
3822 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003823 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003824 i--;
3825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826 }
3827 }
3828
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003829 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3830 if (!doit) {
3831 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003833 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003835
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003836 if (name == null) {
3837 // Remove all sticky broadcasts from this user.
3838 mStickyBroadcasts.remove(userId);
3839 }
3840
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003841 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003842 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003843 if ((name == null || provider.info.packageName.equals(name))
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003844 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3845 if (!doit) {
3846 return true;
3847 }
3848 didSomething = true;
3849 providers.add(provider);
3850 }
3851 }
3852
3853 N = providers.size();
3854 for (i=0; i<N; i++) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003855 removeDyingProviderLocked(null, providers.get(i), true);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003856 }
3857
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003858 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003859 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003860 AttributeCache ac = AttributeCache.instance();
3861 if (ac != null) {
3862 ac.removePackage(name);
3863 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003864 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003865 if (mBooted) {
3866 mMainStack.resumeTopActivityLocked(null);
3867 mMainStack.scheduleIdleLocked();
3868 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003869 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003870
3871 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 }
3873
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003874 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003875 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003877 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003878 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003879 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 + "/" + uid + ")");
3881
3882 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003883 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003884 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07003885 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
3886 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07003887 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 boolean needRestart = false;
3890 if (app.pid > 0 && app.pid != MY_PID) {
3891 int pid = app.pid;
3892 synchronized (mPidsSelfLocked) {
3893 mPidsSelfLocked.remove(pid);
3894 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3895 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003896 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003897 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003898 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003899 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003901 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003903 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 } else {
3905 needRestart = true;
3906 }
3907 }
3908 } else {
3909 mRemovedProcesses.add(app);
3910 }
3911
3912 return needRestart;
3913 }
3914
3915 private final void processStartTimedOutLocked(ProcessRecord app) {
3916 final int pid = app.pid;
3917 boolean gone = false;
3918 synchronized (mPidsSelfLocked) {
3919 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3920 if (knownApp != null && knownApp.thread == null) {
3921 mPidsSelfLocked.remove(pid);
3922 gone = true;
3923 }
3924 }
3925
3926 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003927 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003928 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003929 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003930 mProcessNames.remove(app.processName, app.uid);
3931 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003932 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07003933 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
3934 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07003935 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003936 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003937 // Take care of any launching providers waiting for this process.
3938 checkAppInLaunchingProvidersLocked(app, true);
3939 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003940 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003941 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3942 app.processName, app.setAdj, "start timeout");
3943 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003944 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003945 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003946 try {
3947 IBackupManager bm = IBackupManager.Stub.asInterface(
3948 ServiceManager.getService(Context.BACKUP_SERVICE));
3949 bm.agentDisconnected(app.info.packageName);
3950 } catch (RemoteException e) {
3951 // Can't happen; the backup manager is local
3952 }
3953 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003954 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003955 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003956 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003959 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 }
3961 }
3962
3963 private final boolean attachApplicationLocked(IApplicationThread thread,
3964 int pid) {
3965
3966 // Find the application record that is being attached... either via
3967 // the pid if we are running in multiple processes, or just pull the
3968 // next app record if we are emulating process with anonymous threads.
3969 ProcessRecord app;
3970 if (pid != MY_PID && pid >= 0) {
3971 synchronized (mPidsSelfLocked) {
3972 app = mPidsSelfLocked.get(pid);
3973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 } else {
3975 app = null;
3976 }
3977
3978 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003979 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003981 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003983 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 } else {
3985 try {
3986 thread.scheduleExit();
3987 } catch (Exception e) {
3988 // Ignore exceptions.
3989 }
3990 }
3991 return false;
3992 }
3993
3994 // If this application record is still attached to a previous
3995 // process, clean it up now.
3996 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003997 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 }
3999
4000 // Tell the process all about itself.
4001
Joe Onorato8a9b2202010-02-26 18:56:32 -08004002 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 TAG, "Binding process pid " + pid + " to record " + app);
4004
4005 String processName = app.processName;
4006 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004007 AppDeathRecipient adr = new AppDeathRecipient(
4008 app, pid, thread);
4009 thread.asBinder().linkToDeath(adr, 0);
4010 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 } catch (RemoteException e) {
4012 app.resetPackageList();
4013 startProcessLocked(app, "link fail", processName);
4014 return false;
4015 }
4016
Doug Zongker2bec3d42009-12-04 12:52:44 -08004017 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018
4019 app.thread = thread;
4020 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004021 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4022 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 app.forcingToForeground = null;
4024 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004025 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 app.debugging = false;
4027
4028 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4029
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004030 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004031 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004033 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004034 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004035 }
4036
Joe Onorato8a9b2202010-02-26 18:56:32 -08004037 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 TAG, "New app record " + app
4039 + " thread=" + thread.asBinder() + " pid=" + pid);
4040 try {
4041 int testMode = IApplicationThread.DEBUG_OFF;
4042 if (mDebugApp != null && mDebugApp.equals(processName)) {
4043 testMode = mWaitForDebugger
4044 ? IApplicationThread.DEBUG_WAIT
4045 : IApplicationThread.DEBUG_ON;
4046 app.debugging = true;
4047 if (mDebugTransient) {
4048 mDebugApp = mOrigDebugApp;
4049 mWaitForDebugger = mOrigWaitForDebugger;
4050 }
4051 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004052 String profileFile = app.instrumentationProfileFile;
4053 ParcelFileDescriptor profileFd = null;
4054 boolean profileAutoStop = false;
4055 if (mProfileApp != null && mProfileApp.equals(processName)) {
4056 mProfileProc = app;
4057 profileFile = mProfileFile;
4058 profileFd = mProfileFd;
4059 profileAutoStop = mAutoStopProfiler;
4060 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004061 boolean enableOpenGlTrace = false;
4062 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4063 enableOpenGlTrace = true;
4064 mOpenGlTraceApp = null;
4065 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004066
Christopher Tate181fafa2009-05-14 11:12:14 -07004067 // If the app is being launched for restore or full backup, set it up specially
4068 boolean isRestrictedBackupMode = false;
4069 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4070 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004071 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004072 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4073 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004074
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004075 ensurePackageDexOpt(app.instrumentationInfo != null
4076 ? app.instrumentationInfo.packageName
4077 : app.info.packageName);
4078 if (app.instrumentationClass != null) {
4079 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004080 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004081 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004082 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004083 ApplicationInfo appInfo = app.instrumentationInfo != null
4084 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004085 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004086 if (profileFd != null) {
4087 profileFd = profileFd.dup();
4088 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004089 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004090 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004091 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4092 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004093 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004094 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004095 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004096 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 } catch (Exception e) {
4098 // todo: Yikes! What should we do? For now we will try to
4099 // start another process, but that could easily get us in
4100 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004101 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102
4103 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004104 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 startProcessLocked(app, "bind fail", processName);
4106 return false;
4107 }
4108
4109 // Remove this record from the list of starting applications.
4110 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004111 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4112 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 mProcessesOnHold.remove(app);
4114
4115 boolean badApp = false;
4116 boolean didSomething = false;
4117
4118 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004119 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004120 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004121 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 && processName.equals(hr.processName)) {
4123 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004124 if (mHeadless) {
4125 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4126 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 didSomething = true;
4128 }
4129 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004130 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 + hr.intent.getComponent().flattenToShortString(), e);
4132 badApp = true;
4133 }
4134 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004135 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 }
4137 }
4138
4139 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004140 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004142 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 badApp = true;
4145 }
4146 }
4147
Christopher Tatef46723b2012-01-26 14:19:24 -08004148 // Check if a next-broadcast receiver is in this process...
4149 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004151 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004152 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004153 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 }
4156 }
4157
Christopher Tate181fafa2009-05-14 11:12:14 -07004158 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004159 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004160 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004161 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004162 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004163 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4164 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4165 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004166 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004167 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004168 e.printStackTrace();
4169 }
4170 }
4171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 if (badApp) {
4173 // todo: Also need to kill application to deal with all
4174 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004175 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 return false;
4177 }
4178
4179 if (!didSomething) {
4180 updateOomAdjLocked();
4181 }
4182
4183 return true;
4184 }
4185
4186 public final void attachApplication(IApplicationThread thread) {
4187 synchronized (this) {
4188 int callingPid = Binder.getCallingPid();
4189 final long origId = Binder.clearCallingIdentity();
4190 attachApplicationLocked(thread, callingPid);
4191 Binder.restoreCallingIdentity(origId);
4192 }
4193 }
4194
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004195 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004197 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4198 if (stopProfiling) {
4199 synchronized (this) {
4200 if (mProfileProc == r.app) {
4201 if (mProfileFd != null) {
4202 try {
4203 mProfileFd.close();
4204 } catch (IOException e) {
4205 }
4206 clearProfilerLocked();
4207 }
4208 }
4209 }
4210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 Binder.restoreCallingIdentity(origId);
4212 }
4213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004215 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004216 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004218
4219 synchronized (this) {
4220 updateEventDispatchingLocked();
4221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004222 }
4223
Dianne Hackborn661cd522011-08-22 00:26:20 -07004224 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004225 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004226 mWindowManager.showBootMessage(msg, always);
4227 }
4228
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004229 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004230 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004231 final long token = Binder.clearCallingIdentity();
4232 try {
4233 synchronized (this) {
4234 if (mLockScreenShown) {
4235 mLockScreenShown = false;
4236 comeOutOfSleepIfNeededLocked();
4237 }
4238 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004239 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004240 } finally {
4241 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004242 }
4243 }
4244
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004245 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004246 IntentFilter pkgFilter = new IntentFilter();
4247 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4248 pkgFilter.addDataScheme("package");
4249 mContext.registerReceiver(new BroadcastReceiver() {
4250 @Override
4251 public void onReceive(Context context, Intent intent) {
4252 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4253 if (pkgs != null) {
4254 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004255 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004256 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4257 setResultCode(Activity.RESULT_OK);
4258 return;
4259 }
4260 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004261 }
4262 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004263 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004264 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004265
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004266 synchronized (this) {
4267 // Ensure that any processes we had put on hold are now started
4268 // up.
4269 final int NP = mProcessesOnHold.size();
4270 if (NP > 0) {
4271 ArrayList<ProcessRecord> procs =
4272 new ArrayList<ProcessRecord>(mProcessesOnHold);
4273 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004274 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4275 + procs.get(ip));
4276 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004277 }
4278 }
4279
4280 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004281 // Start looking for apps that are abusing wake locks.
4282 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004283 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004284 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004285 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004286 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004287 for (int i=0; i<mStartedUsers.size(); i++) {
4288 UserStartedState uss = mStartedUsers.valueAt(i);
4289 if (uss.mState == UserStartedState.STATE_BOOTING) {
4290 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004291 final int userId = mStartedUsers.keyAt(i);
4292 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4293 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4294 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004295 null, null, 0, null, null,
4296 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004297 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004298 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004299 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004300 }
4301 }
4302 }
4303
4304 final void ensureBootCompleted() {
4305 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004306 boolean enableScreen;
4307 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004308 booting = mBooting;
4309 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004310 enableScreen = !mBooted;
4311 mBooted = true;
4312 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004313
4314 if (booting) {
4315 finishBooting();
4316 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004317
4318 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004319 enableScreenAfterBoot();
4320 }
4321 }
4322
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004323 public final void activityPaused(IBinder token) {
4324 final long origId = Binder.clearCallingIdentity();
4325 mMainStack.activityPaused(token, false);
4326 Binder.restoreCallingIdentity(origId);
4327 }
4328
4329 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4330 CharSequence description) {
4331 if (localLOGV) Slog.v(
4332 TAG, "Activity stopped: token=" + token);
4333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 // Refuse possible leaked file descriptors
4335 if (icicle != null && icicle.hasFileDescriptors()) {
4336 throw new IllegalArgumentException("File descriptors passed in Bundle");
4337 }
4338
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004339 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004340
4341 final long origId = Binder.clearCallingIdentity();
4342
4343 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004344 r = mMainStack.isInStackLocked(token);
4345 if (r != null) {
4346 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 }
4348 }
4349
4350 if (r != null) {
4351 sendPendingThumbnail(r, null, null, null, false);
4352 }
4353
4354 trimApplications();
4355
4356 Binder.restoreCallingIdentity(origId);
4357 }
4358
4359 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004360 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004361 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 }
4363
4364 public String getCallingPackage(IBinder token) {
4365 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004366 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004367 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004368 }
4369 }
4370
4371 public ComponentName getCallingActivity(IBinder token) {
4372 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004373 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004374 return r != null ? r.intent.getComponent() : null;
4375 }
4376 }
4377
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004378 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004379 ActivityRecord r = mMainStack.isInStackLocked(token);
4380 if (r == null) {
4381 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004382 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004383 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004384 }
4385
4386 public ComponentName getActivityClassForToken(IBinder token) {
4387 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004388 ActivityRecord r = mMainStack.isInStackLocked(token);
4389 if (r == null) {
4390 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004392 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004393 }
4394 }
4395
4396 public String getPackageForToken(IBinder token) {
4397 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004398 ActivityRecord r = mMainStack.isInStackLocked(token);
4399 if (r == null) {
4400 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004401 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004402 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 }
4404 }
4405
4406 public IIntentSender getIntentSender(int type,
4407 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004408 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004409 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004410 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004411 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004412 if (intents != null) {
4413 if (intents.length < 1) {
4414 throw new IllegalArgumentException("Intents array length must be >= 1");
4415 }
4416 for (int i=0; i<intents.length; i++) {
4417 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004418 if (intent != null) {
4419 if (intent.hasFileDescriptors()) {
4420 throw new IllegalArgumentException("File descriptors passed in Intent");
4421 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004422 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004423 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4424 throw new IllegalArgumentException(
4425 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4426 }
4427 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004428 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004429 }
4430 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004431 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004432 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004433 }
4434 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004435 if (options != null) {
4436 if (options.hasFileDescriptors()) {
4437 throw new IllegalArgumentException("File descriptors passed in options");
4438 }
4439 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004441 synchronized(this) {
4442 int callingUid = Binder.getCallingUid();
Dianne Hackborn41203752012-08-31 14:05:51 -07004443 userId = handleIncomingUserLocked(Binder.getCallingPid(), callingUid, userId,
4444 false, true, "getIntentSender", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004446 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004447 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004448 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4449 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004450 String msg = "Permission Denial: getIntentSender() from pid="
4451 + Binder.getCallingPid()
4452 + ", uid=" + Binder.getCallingUid()
4453 + ", (need uid=" + uid + ")"
4454 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004455 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004456 throw new SecurityException(msg);
4457 }
4458 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004459
4460 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004461 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463 } catch (RemoteException e) {
4464 throw new SecurityException(e);
4465 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004466 }
4467 }
4468
Dianne Hackborn41203752012-08-31 14:05:51 -07004469 IIntentSender getIntentSenderLocked(int type, String packageName,
4470 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004471 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4472 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004473 if (DEBUG_MU)
4474 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004475 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004476 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004477 activity = mMainStack.isInStackLocked(token);
4478 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004479 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004481 if (activity.finishing) {
4482 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004483 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004484 }
4485
4486 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4487 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4488 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4489 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4490 |PendingIntent.FLAG_UPDATE_CURRENT);
4491
4492 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4493 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004494 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004495 WeakReference<PendingIntentRecord> ref;
4496 ref = mIntentSenderRecords.get(key);
4497 PendingIntentRecord rec = ref != null ? ref.get() : null;
4498 if (rec != null) {
4499 if (!cancelCurrent) {
4500 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004501 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004502 rec.key.requestIntent.replaceExtras(intents != null ?
4503 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004504 }
4505 if (intents != null) {
4506 intents[intents.length-1] = rec.key.requestIntent;
4507 rec.key.allIntents = intents;
4508 rec.key.allResolvedTypes = resolvedTypes;
4509 } else {
4510 rec.key.allIntents = null;
4511 rec.key.allResolvedTypes = null;
4512 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004514 return rec;
4515 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004516 rec.canceled = true;
4517 mIntentSenderRecords.remove(key);
4518 }
4519 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 return rec;
4521 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004522 rec = new PendingIntentRecord(this, key, callingUid);
4523 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004524 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004525 if (activity.pendingResults == null) {
4526 activity.pendingResults
4527 = new HashSet<WeakReference<PendingIntentRecord>>();
4528 }
4529 activity.pendingResults.add(rec.ref);
4530 }
4531 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 }
4533
4534 public void cancelIntentSender(IIntentSender sender) {
4535 if (!(sender instanceof PendingIntentRecord)) {
4536 return;
4537 }
4538 synchronized(this) {
4539 PendingIntentRecord rec = (PendingIntentRecord)sender;
4540 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004541 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004542 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4543 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 String msg = "Permission Denial: cancelIntentSender() from pid="
4545 + Binder.getCallingPid()
4546 + ", uid=" + Binder.getCallingUid()
4547 + " is not allowed to cancel packges "
4548 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004549 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004550 throw new SecurityException(msg);
4551 }
4552 } catch (RemoteException e) {
4553 throw new SecurityException(e);
4554 }
4555 cancelIntentSenderLocked(rec, true);
4556 }
4557 }
4558
4559 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4560 rec.canceled = true;
4561 mIntentSenderRecords.remove(rec.key);
4562 if (cleanActivity && rec.key.activity != null) {
4563 rec.key.activity.pendingResults.remove(rec.ref);
4564 }
4565 }
4566
4567 public String getPackageForIntentSender(IIntentSender pendingResult) {
4568 if (!(pendingResult instanceof PendingIntentRecord)) {
4569 return null;
4570 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004571 try {
4572 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4573 return res.key.packageName;
4574 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004575 }
4576 return null;
4577 }
4578
Christopher Tatec4a07d12012-04-06 14:19:13 -07004579 public int getUidForIntentSender(IIntentSender sender) {
4580 if (sender instanceof PendingIntentRecord) {
4581 try {
4582 PendingIntentRecord res = (PendingIntentRecord)sender;
4583 return res.uid;
4584 } catch (ClassCastException e) {
4585 }
4586 }
4587 return -1;
4588 }
4589
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004590 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4591 if (!(pendingResult instanceof PendingIntentRecord)) {
4592 return false;
4593 }
4594 try {
4595 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4596 if (res.key.allIntents == null) {
4597 return false;
4598 }
4599 for (int i=0; i<res.key.allIntents.length; i++) {
4600 Intent intent = res.key.allIntents[i];
4601 if (intent.getPackage() != null && intent.getComponent() != null) {
4602 return false;
4603 }
4604 }
4605 return true;
4606 } catch (ClassCastException e) {
4607 }
4608 return false;
4609 }
4610
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004611 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4612 if (!(pendingResult instanceof PendingIntentRecord)) {
4613 return false;
4614 }
4615 try {
4616 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4617 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4618 return true;
4619 }
4620 return false;
4621 } catch (ClassCastException e) {
4622 }
4623 return false;
4624 }
4625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626 public void setProcessLimit(int max) {
4627 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4628 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004629 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004630 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004631 mProcessLimitOverride = max;
4632 }
4633 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004634 }
4635
4636 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004637 synchronized (this) {
4638 return mProcessLimitOverride;
4639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004640 }
4641
4642 void foregroundTokenDied(ForegroundToken token) {
4643 synchronized (ActivityManagerService.this) {
4644 synchronized (mPidsSelfLocked) {
4645 ForegroundToken cur
4646 = mForegroundProcesses.get(token.pid);
4647 if (cur != token) {
4648 return;
4649 }
4650 mForegroundProcesses.remove(token.pid);
4651 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4652 if (pr == null) {
4653 return;
4654 }
4655 pr.forcingToForeground = null;
4656 pr.foregroundServices = false;
4657 }
4658 updateOomAdjLocked();
4659 }
4660 }
4661
4662 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4663 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4664 "setProcessForeground()");
4665 synchronized(this) {
4666 boolean changed = false;
4667
4668 synchronized (mPidsSelfLocked) {
4669 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004670 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004671 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004672 return;
4673 }
4674 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4675 if (oldToken != null) {
4676 oldToken.token.unlinkToDeath(oldToken, 0);
4677 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004678 if (pr != null) {
4679 pr.forcingToForeground = null;
4680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004681 changed = true;
4682 }
4683 if (isForeground && token != null) {
4684 ForegroundToken newToken = new ForegroundToken() {
4685 public void binderDied() {
4686 foregroundTokenDied(this);
4687 }
4688 };
4689 newToken.pid = pid;
4690 newToken.token = token;
4691 try {
4692 token.linkToDeath(newToken, 0);
4693 mForegroundProcesses.put(pid, newToken);
4694 pr.forcingToForeground = token;
4695 changed = true;
4696 } catch (RemoteException e) {
4697 // If the process died while doing this, we will later
4698 // do the cleanup with the process death link.
4699 }
4700 }
4701 }
4702
4703 if (changed) {
4704 updateOomAdjLocked();
4705 }
4706 }
4707 }
4708
4709 // =========================================================
4710 // PERMISSIONS
4711 // =========================================================
4712
4713 static class PermissionController extends IPermissionController.Stub {
4714 ActivityManagerService mActivityManagerService;
4715 PermissionController(ActivityManagerService activityManagerService) {
4716 mActivityManagerService = activityManagerService;
4717 }
4718
4719 public boolean checkPermission(String permission, int pid, int uid) {
4720 return mActivityManagerService.checkPermission(permission, pid,
4721 uid) == PackageManager.PERMISSION_GRANTED;
4722 }
4723 }
4724
4725 /**
4726 * This can be called with or without the global lock held.
4727 */
4728 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004729 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004730 // We might be performing an operation on behalf of an indirect binder
4731 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4732 // client identity accordingly before proceeding.
4733 Identity tlsIdentity = sCallerIdentity.get();
4734 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004735 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004736 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4737 uid = tlsIdentity.uid;
4738 pid = tlsIdentity.pid;
4739 }
4740
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004741 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742 return PackageManager.PERMISSION_GRANTED;
4743 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004744
4745 return ActivityManager.checkComponentPermission(permission, uid,
4746 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004747 }
4748
4749 /**
4750 * As the only public entry point for permissions checking, this method
4751 * can enforce the semantic that requesting a check on a null global
4752 * permission is automatically denied. (Internally a null permission
4753 * string is used when calling {@link #checkComponentPermission} in cases
4754 * when only uid-based security is needed.)
4755 *
4756 * This can be called with or without the global lock held.
4757 */
4758 public int checkPermission(String permission, int pid, int uid) {
4759 if (permission == null) {
4760 return PackageManager.PERMISSION_DENIED;
4761 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004762 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004763 }
4764
4765 /**
4766 * Binder IPC calls go through the public entry point.
4767 * This can be called with or without the global lock held.
4768 */
4769 int checkCallingPermission(String permission) {
4770 return checkPermission(permission,
4771 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004772 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004773 }
4774
4775 /**
4776 * This can be called with or without the global lock held.
4777 */
4778 void enforceCallingPermission(String permission, String func) {
4779 if (checkCallingPermission(permission)
4780 == PackageManager.PERMISSION_GRANTED) {
4781 return;
4782 }
4783
4784 String msg = "Permission Denial: " + func + " from pid="
4785 + Binder.getCallingPid()
4786 + ", uid=" + Binder.getCallingUid()
4787 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004788 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004789 throw new SecurityException(msg);
4790 }
4791
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004792 /**
4793 * Determine if UID is holding permissions required to access {@link Uri} in
4794 * the given {@link ProviderInfo}. Final permission checking is always done
4795 * in {@link ContentProvider}.
4796 */
4797 private final boolean checkHoldingPermissionsLocked(
4798 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004799 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4800 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004801
4802 if (pi.applicationInfo.uid == uid) {
4803 return true;
4804 } else if (!pi.exported) {
4805 return false;
4806 }
4807
4808 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4809 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004810 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004811 // check if target holds top-level <provider> permissions
4812 if (!readMet && pi.readPermission != null
4813 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4814 readMet = true;
4815 }
4816 if (!writeMet && pi.writePermission != null
4817 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4818 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004819 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004820
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004821 // track if unprotected read/write is allowed; any denied
4822 // <path-permission> below removes this ability
4823 boolean allowDefaultRead = pi.readPermission == null;
4824 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004825
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004826 // check if target holds any <path-permission> that match uri
4827 final PathPermission[] pps = pi.pathPermissions;
4828 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004829 final String path = uri.getPath();
4830 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004831 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004832 i--;
4833 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004834 if (pp.match(path)) {
4835 if (!readMet) {
4836 final String pprperm = pp.getReadPermission();
4837 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4838 + pprperm + " for " + pp.getPath()
4839 + ": match=" + pp.match(path)
4840 + " check=" + pm.checkUidPermission(pprperm, uid));
4841 if (pprperm != null) {
4842 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4843 readMet = true;
4844 } else {
4845 allowDefaultRead = false;
4846 }
4847 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004848 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004849 if (!writeMet) {
4850 final String ppwperm = pp.getWritePermission();
4851 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4852 + ppwperm + " for " + pp.getPath()
4853 + ": match=" + pp.match(path)
4854 + " check=" + pm.checkUidPermission(ppwperm, uid));
4855 if (ppwperm != null) {
4856 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4857 writeMet = true;
4858 } else {
4859 allowDefaultWrite = false;
4860 }
4861 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004862 }
4863 }
4864 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004865 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004866
4867 // grant unprotected <provider> read/write, if not blocked by
4868 // <path-permission> above
4869 if (allowDefaultRead) readMet = true;
4870 if (allowDefaultWrite) writeMet = true;
4871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004872 } catch (RemoteException e) {
4873 return false;
4874 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004875
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004876 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004877 }
4878
4879 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4880 int modeFlags) {
4881 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004882 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883 return true;
4884 }
4885 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4886 if (perms == null) return false;
4887 UriPermission perm = perms.get(uri);
4888 if (perm == null) return false;
4889 return (modeFlags&perm.modeFlags) == modeFlags;
4890 }
4891
4892 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004893 enforceNotIsolatedCaller("checkUriPermission");
4894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004895 // Another redirected-binder-call permissions check as in
4896 // {@link checkComponentPermission}.
4897 Identity tlsIdentity = sCallerIdentity.get();
4898 if (tlsIdentity != null) {
4899 uid = tlsIdentity.uid;
4900 pid = tlsIdentity.pid;
4901 }
4902
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004903 uid = UserHandle.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004904 // Our own process gets to do everything.
4905 if (pid == MY_PID) {
4906 return PackageManager.PERMISSION_GRANTED;
4907 }
4908 synchronized(this) {
4909 return checkUriPermissionLocked(uri, uid, modeFlags)
4910 ? PackageManager.PERMISSION_GRANTED
4911 : PackageManager.PERMISSION_DENIED;
4912 }
4913 }
4914
Dianne Hackborn39792d22010-08-19 18:01:52 -07004915 /**
4916 * Check if the targetPkg can be granted permission to access uri by
4917 * the callingUid using the given modeFlags. Throws a security exception
4918 * if callingUid is not allowed to do this. Returns the uid of the target
4919 * if the URI permission grant should be performed; returns -1 if it is not
4920 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004921 * If you already know the uid of the target, you can supply it in
4922 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004923 */
4924 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004925 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004926 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4927 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4928 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004929 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004930 }
4931
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004932 if (targetPkg != null) {
4933 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4934 "Checking grant " + targetPkg + " permission to " + uri);
4935 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004936
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004937 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004938
4939 // If this is not a content: uri, we can't do anything with it.
4940 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004941 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004942 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004943 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004944 }
4945
4946 String name = uri.getAuthority();
4947 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004948 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004949 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004950 if (cpr != null) {
4951 pi = cpr.info;
4952 } else {
4953 try {
4954 pi = pm.resolveContentProvider(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004955 PackageManager.GET_URI_PERMISSION_PATTERNS, UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004956 } catch (RemoteException ex) {
4957 }
4958 }
4959 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004960 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004961 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004962 }
4963
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004964 int targetUid = lastTargetUid;
4965 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004966 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004967 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004968 if (targetUid < 0) {
4969 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4970 "Can't grant URI permission no uid for: " + targetPkg);
4971 return -1;
4972 }
4973 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004974 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 }
4977
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004978 if (targetUid >= 0) {
4979 // First... does the target actually need this permission?
4980 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4981 // No need to grant the target this permission.
4982 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4983 "Target " + targetPkg + " already has full permission to " + uri);
4984 return -1;
4985 }
4986 } else {
4987 // First... there is no target package, so can anyone access it?
4988 boolean allowed = pi.exported;
4989 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4990 if (pi.readPermission != null) {
4991 allowed = false;
4992 }
4993 }
4994 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4995 if (pi.writePermission != null) {
4996 allowed = false;
4997 }
4998 }
4999 if (allowed) {
5000 return -1;
5001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005002 }
5003
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005004 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005005 if (!pi.grantUriPermissions) {
5006 throw new SecurityException("Provider " + pi.packageName
5007 + "/" + pi.name
5008 + " does not allow granting of Uri permissions (uri "
5009 + uri + ")");
5010 }
5011 if (pi.uriPermissionPatterns != null) {
5012 final int N = pi.uriPermissionPatterns.length;
5013 boolean allowed = false;
5014 for (int i=0; i<N; i++) {
5015 if (pi.uriPermissionPatterns[i] != null
5016 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5017 allowed = true;
5018 break;
5019 }
5020 }
5021 if (!allowed) {
5022 throw new SecurityException("Provider " + pi.packageName
5023 + "/" + pi.name
5024 + " does not allow granting of permission to path of Uri "
5025 + uri);
5026 }
5027 }
5028
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005029 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005030 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005031 if (callingUid != Process.myUid()) {
5032 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5033 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5034 throw new SecurityException("Uid " + callingUid
5035 + " does not have permission to uri " + uri);
5036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005037 }
5038 }
5039
Dianne Hackborn39792d22010-08-19 18:01:52 -07005040 return targetUid;
5041 }
5042
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005043 public int checkGrantUriPermission(int callingUid, String targetPkg,
5044 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005045 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005046 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005047 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005048 }
5049 }
5050
Dianne Hackborn39792d22010-08-19 18:01:52 -07005051 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5052 Uri uri, int modeFlags, UriPermissionOwner owner) {
5053 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5054 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5055 if (modeFlags == 0) {
5056 return;
5057 }
5058
5059 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005060 // to the uri, and the target doesn't. Let's now give this to
5061 // the target.
5062
Joe Onorato8a9b2202010-02-26 18:56:32 -08005063 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005064 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005066 HashMap<Uri, UriPermission> targetUris
5067 = mGrantedUriPermissions.get(targetUid);
5068 if (targetUris == null) {
5069 targetUris = new HashMap<Uri, UriPermission>();
5070 mGrantedUriPermissions.put(targetUid, targetUris);
5071 }
5072
5073 UriPermission perm = targetUris.get(uri);
5074 if (perm == null) {
5075 perm = new UriPermission(targetUid, uri);
5076 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005077 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005079 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005080 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005081 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005082 } else {
5083 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5084 perm.readOwners.add(owner);
5085 owner.addReadPermission(perm);
5086 }
5087 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5088 perm.writeOwners.add(owner);
5089 owner.addWritePermission(perm);
5090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005091 }
5092 }
5093
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005094 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5095 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005096 if (targetPkg == null) {
5097 throw new NullPointerException("targetPkg");
5098 }
5099
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005100 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005101 if (targetUid < 0) {
5102 return;
5103 }
5104
5105 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5106 }
5107
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005108 static class NeededUriGrants extends ArrayList<Uri> {
5109 final String targetPkg;
5110 final int targetUid;
5111 final int flags;
5112
5113 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5114 targetPkg = _targetPkg;
5115 targetUid = _targetUid;
5116 flags = _flags;
5117 }
5118 }
5119
Dianne Hackborn39792d22010-08-19 18:01:52 -07005120 /**
5121 * Like checkGrantUriPermissionLocked, but takes an Intent.
5122 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005123 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5124 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005125 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005126 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5127 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005128 + " from " + intent + "; flags=0x"
5129 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5130
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005131 if (targetPkg == null) {
5132 throw new NullPointerException("targetPkg");
5133 }
5134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005135 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005136 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005137 }
5138 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005139 ClipData clip = intent.getClipData();
5140 if (data == null && clip == null) {
5141 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005142 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005143 if (data != null) {
5144 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5145 mode, needed != null ? needed.targetUid : -1);
5146 if (target > 0) {
5147 if (needed == null) {
5148 needed = new NeededUriGrants(targetPkg, target, mode);
5149 }
5150 needed.add(data);
5151 }
5152 }
5153 if (clip != null) {
5154 for (int i=0; i<clip.getItemCount(); i++) {
5155 Uri uri = clip.getItemAt(i).getUri();
5156 if (uri != null) {
5157 int target = -1;
5158 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5159 mode, needed != null ? needed.targetUid : -1);
5160 if (target > 0) {
5161 if (needed == null) {
5162 needed = new NeededUriGrants(targetPkg, target, mode);
5163 }
5164 needed.add(uri);
5165 }
5166 } else {
5167 Intent clipIntent = clip.getItemAt(i).getIntent();
5168 if (clipIntent != null) {
5169 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5170 callingUid, targetPkg, clipIntent, mode, needed);
5171 if (newNeeded != null) {
5172 needed = newNeeded;
5173 }
5174 }
5175 }
5176 }
5177 }
5178
5179 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005180 }
5181
5182 /**
5183 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5184 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005185 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5186 UriPermissionOwner owner) {
5187 if (needed != null) {
5188 for (int i=0; i<needed.size(); i++) {
5189 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5190 needed.get(i), needed.flags, owner);
5191 }
5192 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005193 }
5194
5195 void grantUriPermissionFromIntentLocked(int callingUid,
5196 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005197 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005198 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005199 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005200 return;
5201 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005202
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005203 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005204 }
5205
5206 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5207 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005208 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 synchronized(this) {
5210 final ProcessRecord r = getRecordForAppLocked(caller);
5211 if (r == null) {
5212 throw new SecurityException("Unable to find app for caller "
5213 + caller
5214 + " when granting permission to uri " + uri);
5215 }
5216 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005217 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005218 }
5219 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005220 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005221 }
5222
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005223 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224 null);
5225 }
5226 }
5227
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005228 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005229 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5230 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5231 HashMap<Uri, UriPermission> perms
5232 = mGrantedUriPermissions.get(perm.uid);
5233 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005234 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005235 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005236 perms.remove(perm.uri);
5237 if (perms.size() == 0) {
5238 mGrantedUriPermissions.remove(perm.uid);
5239 }
5240 }
5241 }
5242 }
5243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5245 int modeFlags) {
5246 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5247 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5248 if (modeFlags == 0) {
5249 return;
5250 }
5251
Joe Onorato8a9b2202010-02-26 18:56:32 -08005252 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005253 "Revoking all granted permissions to " + uri);
5254
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005255 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005256
5257 final String authority = uri.getAuthority();
5258 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005259 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005260 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005261 if (cpr != null) {
5262 pi = cpr.info;
5263 } else {
5264 try {
5265 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005266 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005267 } catch (RemoteException ex) {
5268 }
5269 }
5270 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005271 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005272 return;
5273 }
5274
5275 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005276 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005277 // Right now, if you are not the original owner of the permission,
5278 // you are not allowed to revoke it.
5279 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5280 throw new SecurityException("Uid " + callingUid
5281 + " does not have permission to uri " + uri);
5282 //}
5283 }
5284
5285 // Go through all of the permissions and remove any that match.
5286 final List<String> SEGMENTS = uri.getPathSegments();
5287 if (SEGMENTS != null) {
5288 final int NS = SEGMENTS.size();
5289 int N = mGrantedUriPermissions.size();
5290 for (int i=0; i<N; i++) {
5291 HashMap<Uri, UriPermission> perms
5292 = mGrantedUriPermissions.valueAt(i);
5293 Iterator<UriPermission> it = perms.values().iterator();
5294 toploop:
5295 while (it.hasNext()) {
5296 UriPermission perm = it.next();
5297 Uri targetUri = perm.uri;
5298 if (!authority.equals(targetUri.getAuthority())) {
5299 continue;
5300 }
5301 List<String> targetSegments = targetUri.getPathSegments();
5302 if (targetSegments == null) {
5303 continue;
5304 }
5305 if (targetSegments.size() < NS) {
5306 continue;
5307 }
5308 for (int j=0; j<NS; j++) {
5309 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5310 continue toploop;
5311 }
5312 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005313 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005314 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005315 perm.clearModes(modeFlags);
5316 if (perm.modeFlags == 0) {
5317 it.remove();
5318 }
5319 }
5320 if (perms.size() == 0) {
5321 mGrantedUriPermissions.remove(
5322 mGrantedUriPermissions.keyAt(i));
5323 N--;
5324 i--;
5325 }
5326 }
5327 }
5328 }
5329
5330 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5331 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005332 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005333 synchronized(this) {
5334 final ProcessRecord r = getRecordForAppLocked(caller);
5335 if (r == null) {
5336 throw new SecurityException("Unable to find app for caller "
5337 + caller
5338 + " when revoking permission to uri " + uri);
5339 }
5340 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005341 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005342 return;
5343 }
5344
5345 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5346 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5347 if (modeFlags == 0) {
5348 return;
5349 }
5350
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005351 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005352
5353 final String authority = uri.getAuthority();
5354 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005355 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005356 if (cpr != null) {
5357 pi = cpr.info;
5358 } else {
5359 try {
5360 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005361 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005362 } catch (RemoteException ex) {
5363 }
5364 }
5365 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005366 Slog.w(TAG, "No content provider found for permission revoke: "
5367 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005368 return;
5369 }
5370
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005371 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005372 }
5373 }
5374
Dianne Hackborn7e269642010-08-25 19:50:20 -07005375 @Override
5376 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005377 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005378 synchronized(this) {
5379 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5380 return owner.getExternalTokenLocked();
5381 }
5382 }
5383
5384 @Override
5385 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5386 Uri uri, int modeFlags) {
5387 synchronized(this) {
5388 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5389 if (owner == null) {
5390 throw new IllegalArgumentException("Unknown owner: " + token);
5391 }
5392 if (fromUid != Binder.getCallingUid()) {
5393 if (Binder.getCallingUid() != Process.myUid()) {
5394 // Only system code can grant URI permissions on behalf
5395 // of other users.
5396 throw new SecurityException("nice try");
5397 }
5398 }
5399 if (targetPkg == null) {
5400 throw new IllegalArgumentException("null target");
5401 }
5402 if (uri == null) {
5403 throw new IllegalArgumentException("null uri");
5404 }
5405
5406 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5407 }
5408 }
5409
5410 @Override
5411 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5412 synchronized(this) {
5413 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5414 if (owner == null) {
5415 throw new IllegalArgumentException("Unknown owner: " + token);
5416 }
5417
5418 if (uri == null) {
5419 owner.removeUriPermissionsLocked(mode);
5420 } else {
5421 owner.removeUriPermissionLocked(uri, mode);
5422 }
5423 }
5424 }
5425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005426 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5427 synchronized (this) {
5428 ProcessRecord app =
5429 who != null ? getRecordForAppLocked(who) : null;
5430 if (app == null) return;
5431
5432 Message msg = Message.obtain();
5433 msg.what = WAIT_FOR_DEBUGGER_MSG;
5434 msg.obj = app;
5435 msg.arg1 = waiting ? 1 : 0;
5436 mHandler.sendMessage(msg);
5437 }
5438 }
5439
5440 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005441 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5442 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005444 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005445 outInfo.threshold = homeAppMem;
5446 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5447 outInfo.hiddenAppThreshold = hiddenAppMem;
5448 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005449 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005450 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5451 ProcessList.VISIBLE_APP_ADJ);
5452 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5453 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 }
5455
5456 // =========================================================
5457 // TASK MANAGEMENT
5458 // =========================================================
5459
5460 public List getTasks(int maxNum, int flags,
5461 IThumbnailReceiver receiver) {
5462 ArrayList list = new ArrayList();
5463
5464 PendingThumbnailsRecord pending = null;
5465 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005466 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005467
5468 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005469 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5471 + ", receiver=" + receiver);
5472
5473 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5474 != PackageManager.PERMISSION_GRANTED) {
5475 if (receiver != null) {
5476 // If the caller wants to wait for pending thumbnails,
5477 // it ain't gonna get them.
5478 try {
5479 receiver.finished();
5480 } catch (RemoteException ex) {
5481 }
5482 }
5483 String msg = "Permission Denial: getTasks() from pid="
5484 + Binder.getCallingPid()
5485 + ", uid=" + Binder.getCallingUid()
5486 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005487 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 throw new SecurityException(msg);
5489 }
5490
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005491 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005492 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005493 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005494 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 TaskRecord curTask = null;
5496 int numActivities = 0;
5497 int numRunning = 0;
5498 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005499 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005500 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005501 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005502
5503 // Initialize state for next task if needed.
5504 if (top == null ||
5505 (top.state == ActivityState.INITIALIZING
5506 && top.task == r.task)) {
5507 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005508 curTask = r.task;
5509 numActivities = numRunning = 0;
5510 }
5511
5512 // Add 'r' into the current task.
5513 numActivities++;
5514 if (r.app != null && r.app.thread != null) {
5515 numRunning++;
5516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517
Joe Onorato8a9b2202010-02-26 18:56:32 -08005518 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 TAG, r.intent.getComponent().flattenToShortString()
5520 + ": task=" + r.task);
5521
5522 // If the next one is a different task, generate a new
5523 // TaskInfo entry for what we have.
5524 if (next == null || next.task != curTask) {
5525 ActivityManager.RunningTaskInfo ci
5526 = new ActivityManager.RunningTaskInfo();
5527 ci.id = curTask.taskId;
5528 ci.baseActivity = r.intent.getComponent();
5529 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005530 if (top.thumbHolder != null) {
5531 ci.description = top.thumbHolder.lastDescription;
5532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005533 ci.numActivities = numActivities;
5534 ci.numRunning = numRunning;
5535 //System.out.println(
5536 // "#" + maxNum + ": " + " descr=" + ci.description);
5537 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005538 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 TAG, "State=" + top.state + "Idle=" + top.idle
5540 + " app=" + top.app
5541 + " thr=" + (top.app != null ? top.app.thread : null));
5542 if (top.state == ActivityState.RESUMED
5543 || top.state == ActivityState.PAUSING) {
5544 if (top.idle && top.app != null
5545 && top.app.thread != null) {
5546 topRecord = top;
5547 topThumbnail = top.app.thread;
5548 } else {
5549 top.thumbnailNeeded = true;
5550 }
5551 }
5552 if (pending == null) {
5553 pending = new PendingThumbnailsRecord(receiver);
5554 }
5555 pending.pendingRecords.add(top);
5556 }
5557 list.add(ci);
5558 maxNum--;
5559 top = null;
5560 }
5561 }
5562
5563 if (pending != null) {
5564 mPendingThumbnails.add(pending);
5565 }
5566 }
5567
Joe Onorato8a9b2202010-02-26 18:56:32 -08005568 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569
5570 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005571 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005573 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005575 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005576 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 }
5578 }
5579
5580 if (pending == null && receiver != null) {
5581 // In this case all thumbnails were available and the client
5582 // is being asked to be told when the remaining ones come in...
5583 // which is unusually, since the top-most currently running
5584 // activity should never have a canned thumbnail! Oh well.
5585 try {
5586 receiver.finished();
5587 } catch (RemoteException ex) {
5588 }
5589 }
5590
5591 return list;
5592 }
5593
5594 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005595 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005596 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005597 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07005598 // Check if the caller is holding permissions for cross-user requests.
5599 if (checkComponentPermission(
5600 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5601 Binder.getCallingPid(), callingUid, -1, true)
5602 != PackageManager.PERMISSION_GRANTED) {
5603 String msg = "Permission Denial: "
5604 + "Request to get recent tasks for user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005605 + " but is calling from user " + UserHandle.getUserId(callingUid)
Amith Yamasani82644082012-08-03 13:09:11 -07005606 + "; this requires "
5607 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5608 Slog.w(TAG, msg);
5609 throw new SecurityException(msg);
5610 } else {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005611 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07005612 userId = mCurrentUserId;
5613 }
5614 }
5615 }
5616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005617 synchronized (this) {
5618 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5619 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005620 final boolean detailed = checkCallingPermission(
5621 android.Manifest.permission.GET_DETAILED_TASKS)
5622 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005624 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005626 final int N = mRecentTasks.size();
5627 ArrayList<ActivityManager.RecentTaskInfo> res
5628 = new ArrayList<ActivityManager.RecentTaskInfo>(
5629 maxNum < N ? maxNum : N);
5630 for (int i=0; i<N && maxNum > 0; i++) {
5631 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005632 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005633 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005634 // Return the entry if desired by the caller. We always return
5635 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005636 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005637 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5638 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005639
Dianne Hackborn905577f2011-09-07 18:31:28 -07005640 if (i == 0
5641 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 || (tr.intent == null)
5643 || ((tr.intent.getFlags()
5644 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5645 ActivityManager.RecentTaskInfo rti
5646 = new ActivityManager.RecentTaskInfo();
5647 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005648 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 rti.baseIntent = new Intent(
5650 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005651 if (!detailed) {
5652 rti.baseIntent.replaceExtras((Bundle)null);
5653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005655 rti.description = tr.lastDescription;
5656
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005657 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5658 // Check whether this activity is currently available.
5659 try {
5660 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005661 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005662 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005663 continue;
5664 }
5665 } else if (rti.baseIntent != null) {
5666 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005667 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005668 continue;
5669 }
5670 }
5671 } catch (RemoteException e) {
5672 // Will never happen.
5673 }
5674 }
5675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005676 res.add(rti);
5677 maxNum--;
5678 }
5679 }
5680 return res;
5681 }
5682 }
5683
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005684 private TaskRecord taskForIdLocked(int id) {
5685 final int N = mRecentTasks.size();
5686 for (int i=0; i<N; i++) {
5687 TaskRecord tr = mRecentTasks.get(i);
5688 if (tr.taskId == id) {
5689 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005690 }
5691 }
5692 return null;
5693 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005694
5695 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5696 synchronized (this) {
5697 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5698 "getTaskThumbnails()");
5699 TaskRecord tr = taskForIdLocked(id);
5700 if (tr != null) {
5701 return mMainStack.getTaskThumbnailsLocked(tr);
5702 }
5703 }
5704 return null;
5705 }
5706
5707 public boolean removeSubTask(int taskId, int subTaskIndex) {
5708 synchronized (this) {
5709 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5710 "removeSubTask()");
5711 long ident = Binder.clearCallingIdentity();
5712 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005713 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5714 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005715 } finally {
5716 Binder.restoreCallingIdentity(ident);
5717 }
5718 }
5719 }
5720
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005721 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5722 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005723 Intent baseIntent = new Intent(
5724 tr.intent != null ? tr.intent : tr.affinityIntent);
5725 ComponentName component = baseIntent.getComponent();
5726 if (component == null) {
5727 Slog.w(TAG, "Now component for base intent of task: " + tr);
5728 return;
5729 }
5730
5731 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005732 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005733
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005734 if (killProcesses) {
5735 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005736 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005737 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005738 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5739 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5740 for (int i=0; i<uids.size(); i++) {
5741 ProcessRecord proc = uids.valueAt(i);
5742 if (proc.userId != tr.userId) {
5743 continue;
5744 }
5745 if (!proc.pkgList.contains(pkg)) {
5746 continue;
5747 }
5748 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005749 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005750 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005751
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005752 // Kill the running processes.
5753 for (int i=0; i<procs.size(); i++) {
5754 ProcessRecord pr = procs.get(i);
5755 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5756 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5757 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5758 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005759 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005760 Process.killProcessQuiet(pr.pid);
5761 } else {
5762 pr.waitingToKill = "remove task";
5763 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005764 }
5765 }
5766 }
5767
5768 public boolean removeTask(int taskId, int flags) {
5769 synchronized (this) {
5770 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5771 "removeTask()");
5772 long ident = Binder.clearCallingIdentity();
5773 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005774 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5775 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005776 if (r != null) {
5777 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005778 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005779 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005780 } else {
5781 TaskRecord tr = null;
5782 int i=0;
5783 while (i < mRecentTasks.size()) {
5784 TaskRecord t = mRecentTasks.get(i);
5785 if (t.taskId == taskId) {
5786 tr = t;
5787 break;
5788 }
5789 i++;
5790 }
5791 if (tr != null) {
5792 if (tr.numActivities <= 0) {
5793 // Caller is just removing a recent task that is
5794 // not actively running. That is easy!
5795 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005796 cleanUpRemovedTaskLocked(tr, flags);
5797 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005798 } else {
5799 Slog.w(TAG, "removeTask: task " + taskId
5800 + " does not have activities to remove, "
5801 + " but numActivities=" + tr.numActivities
5802 + ": " + tr);
5803 }
5804 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005805 }
5806 } finally {
5807 Binder.restoreCallingIdentity(ident);
5808 }
5809 }
5810 return false;
5811 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005813 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5814 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005815 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 TaskRecord jt = startTask;
5817
5818 // First look backwards
5819 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005820 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821 if (r.task != jt) {
5822 jt = r.task;
5823 if (affinity.equals(jt.affinity)) {
5824 return j;
5825 }
5826 }
5827 }
5828
5829 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005830 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 jt = startTask;
5832 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005833 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 if (r.task != jt) {
5835 if (affinity.equals(jt.affinity)) {
5836 return j;
5837 }
5838 jt = r.task;
5839 }
5840 }
5841
5842 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005843 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 return N-1;
5845 }
5846
5847 return -1;
5848 }
5849
5850 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005851 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005852 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005853 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005854 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5855 "moveTaskToFront()");
5856
5857 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005858 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5859 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005860 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005861 return;
5862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005863 final long origId = Binder.clearCallingIdentity();
5864 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005865 TaskRecord tr = taskForIdLocked(task);
5866 if (tr != null) {
5867 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5868 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005870 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5871 // Caller wants the home activity moved with it. To accomplish this,
5872 // we'll just move the home task to the top first.
5873 mMainStack.moveHomeToFrontLocked();
5874 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005875 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005876 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005878 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5879 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005881 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5882 mMainStack.mUserLeaving = true;
5883 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005884 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5885 // Caller wants the home activity moved with it. To accomplish this,
5886 // we'll just move the home task to the top first.
5887 mMainStack.moveHomeToFrontLocked();
5888 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005889 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 return;
5891 }
5892 }
5893 } finally {
5894 Binder.restoreCallingIdentity(origId);
5895 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005896 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 }
5898 }
5899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 public void moveTaskToBack(int task) {
5901 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5902 "moveTaskToBack()");
5903
5904 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005905 if (mMainStack.mResumedActivity != null
5906 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005907 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5908 Binder.getCallingUid(), "Task to back")) {
5909 return;
5910 }
5911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005912 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005913 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005914 Binder.restoreCallingIdentity(origId);
5915 }
5916 }
5917
5918 /**
5919 * Moves an activity, and all of the other activities within the same task, to the bottom
5920 * of the history stack. The activity's order within the task is unchanged.
5921 *
5922 * @param token A reference to the activity we wish to move
5923 * @param nonRoot If false then this only works if the activity is the root
5924 * of a task; if true it will work for any activity in a task.
5925 * @return Returns true if the move completed, false if not.
5926 */
5927 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005928 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005929 synchronized(this) {
5930 final long origId = Binder.clearCallingIdentity();
5931 int taskId = getTaskForActivityLocked(token, !nonRoot);
5932 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005933 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 }
5935 Binder.restoreCallingIdentity(origId);
5936 }
5937 return false;
5938 }
5939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 public void moveTaskBackwards(int task) {
5941 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5942 "moveTaskBackwards()");
5943
5944 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005945 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5946 Binder.getCallingUid(), "Task backwards")) {
5947 return;
5948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005949 final long origId = Binder.clearCallingIdentity();
5950 moveTaskBackwardsLocked(task);
5951 Binder.restoreCallingIdentity(origId);
5952 }
5953 }
5954
5955 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005956 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957 }
5958
5959 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5960 synchronized(this) {
5961 return getTaskForActivityLocked(token, onlyRoot);
5962 }
5963 }
5964
5965 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005966 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 TaskRecord lastTask = null;
5968 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005969 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005970 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005971 if (!onlyRoot || lastTask != r.task) {
5972 return r.task.taskId;
5973 }
5974 return -1;
5975 }
5976 lastTask = r.task;
5977 }
5978
5979 return -1;
5980 }
5981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 // =========================================================
5983 // THUMBNAILS
5984 // =========================================================
5985
5986 public void reportThumbnail(IBinder token,
5987 Bitmap thumbnail, CharSequence description) {
5988 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5989 final long origId = Binder.clearCallingIdentity();
5990 sendPendingThumbnail(null, token, thumbnail, description, true);
5991 Binder.restoreCallingIdentity(origId);
5992 }
5993
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005994 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005995 Bitmap thumbnail, CharSequence description, boolean always) {
5996 TaskRecord task = null;
5997 ArrayList receivers = null;
5998
5999 //System.out.println("Send pending thumbnail: " + r);
6000
6001 synchronized(this) {
6002 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006003 r = mMainStack.isInStackLocked(token);
6004 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006005 return;
6006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006008 if (thumbnail == null && r.thumbHolder != null) {
6009 thumbnail = r.thumbHolder.lastThumbnail;
6010 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 }
6012 if (thumbnail == null && !always) {
6013 // If there is no thumbnail, and this entry is not actually
6014 // going away, then abort for now and pick up the next
6015 // thumbnail we get.
6016 return;
6017 }
6018 task = r.task;
6019
6020 int N = mPendingThumbnails.size();
6021 int i=0;
6022 while (i<N) {
6023 PendingThumbnailsRecord pr =
6024 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6025 //System.out.println("Looking in " + pr.pendingRecords);
6026 if (pr.pendingRecords.remove(r)) {
6027 if (receivers == null) {
6028 receivers = new ArrayList();
6029 }
6030 receivers.add(pr);
6031 if (pr.pendingRecords.size() == 0) {
6032 pr.finished = true;
6033 mPendingThumbnails.remove(i);
6034 N--;
6035 continue;
6036 }
6037 }
6038 i++;
6039 }
6040 }
6041
6042 if (receivers != null) {
6043 final int N = receivers.size();
6044 for (int i=0; i<N; i++) {
6045 try {
6046 PendingThumbnailsRecord pr =
6047 (PendingThumbnailsRecord)receivers.get(i);
6048 pr.receiver.newThumbnail(
6049 task != null ? task.taskId : -1, thumbnail, description);
6050 if (pr.finished) {
6051 pr.receiver.finished();
6052 }
6053 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006054 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 }
6056 }
6057 }
6058 }
6059
6060 // =========================================================
6061 // CONTENT PROVIDERS
6062 // =========================================================
6063
Jeff Brown10e89712011-07-08 18:52:57 -07006064 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6065 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006067 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006068 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006069 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070 } catch (RemoteException ex) {
6071 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006072 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006073 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6074 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006075 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006076 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 for (int i=0; i<N; i++) {
6078 ProviderInfo cpi =
6079 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006080 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6081 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006082 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006083 // This is a singleton provider, but a user besides the
6084 // default user is asking to initialize a process it runs
6085 // in... well, no, it doesn't actually run in this process,
6086 // it runs in the process of the default user. Get rid of it.
6087 providers.remove(i);
6088 N--;
6089 continue;
6090 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006091
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006092 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006093 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006095 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006096 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006098 if (DEBUG_MU)
6099 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 app.pubProviders.put(cpi.name, cpr);
6101 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006102 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103 }
6104 }
6105 return providers;
6106 }
6107
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006108 /**
6109 * Check if {@link ProcessRecord} has a possible chance at accessing the
6110 * given {@link ProviderInfo}. Final permission checking is always done
6111 * in {@link ContentProvider}.
6112 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006114 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006116 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006118 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006119 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 return null;
6121 }
6122 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006123 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 == PackageManager.PERMISSION_GRANTED) {
6125 return null;
6126 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006127
6128 PathPermission[] pps = cpi.pathPermissions;
6129 if (pps != null) {
6130 int i = pps.length;
6131 while (i > 0) {
6132 i--;
6133 PathPermission pp = pps[i];
6134 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006135 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006136 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006137 return null;
6138 }
6139 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006140 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006141 == PackageManager.PERMISSION_GRANTED) {
6142 return null;
6143 }
6144 }
6145 }
6146
Dianne Hackbornb424b632010-08-18 15:59:05 -07006147 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6148 if (perms != null) {
6149 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6150 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6151 return null;
6152 }
6153 }
6154 }
6155
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006156 String msg;
6157 if (!cpi.exported) {
6158 msg = "Permission Denial: opening provider " + cpi.name
6159 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6160 + ", uid=" + callingUid + ") that is not exported from uid "
6161 + cpi.applicationInfo.uid;
6162 } else {
6163 msg = "Permission Denial: opening provider " + cpi.name
6164 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6165 + ", uid=" + callingUid + ") requires "
6166 + cpi.readPermission + " or " + cpi.writePermission;
6167 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006168 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 return msg;
6170 }
6171
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006172 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6173 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006174 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006175 for (int i=0; i<r.conProviders.size(); i++) {
6176 ContentProviderConnection conn = r.conProviders.get(i);
6177 if (conn.provider == cpr) {
6178 if (DEBUG_PROVIDER) Slog.v(TAG,
6179 "Adding provider requested by "
6180 + r.processName + " from process "
6181 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6182 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6183 if (stable) {
6184 conn.stableCount++;
6185 conn.numStableIncs++;
6186 } else {
6187 conn.unstableCount++;
6188 conn.numUnstableIncs++;
6189 }
6190 return conn;
6191 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006192 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006193 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6194 if (stable) {
6195 conn.stableCount = 1;
6196 conn.numStableIncs = 1;
6197 } else {
6198 conn.unstableCount = 1;
6199 conn.numUnstableIncs = 1;
6200 }
6201 cpr.connections.add(conn);
6202 r.conProviders.add(conn);
6203 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006204 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006205 cpr.addExternalProcessHandleLocked(externalProcessToken);
6206 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006207 }
6208
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006209 boolean decProviderCountLocked(ContentProviderConnection conn,
6210 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6211 if (conn != null) {
6212 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006213 if (DEBUG_PROVIDER) Slog.v(TAG,
6214 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006215 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006216 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006217 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6218 if (stable) {
6219 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006220 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006221 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006222 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006223 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6224 cpr.connections.remove(conn);
6225 conn.client.conProviders.remove(conn);
6226 return true;
6227 }
6228 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006229 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006230 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006231 return false;
6232 }
6233
Amith Yamasani742a6712011-05-04 14:49:28 -07006234 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006235 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006237 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 ProviderInfo cpi = null;
6239
6240 synchronized(this) {
6241 ProcessRecord r = null;
6242 if (caller != null) {
6243 r = getRecordForAppLocked(caller);
6244 if (r == null) {
6245 throw new SecurityException(
6246 "Unable to find app for caller " + caller
6247 + " (pid=" + Binder.getCallingPid()
6248 + ") when getting content provider " + name);
6249 }
Dianne Hackborn41203752012-08-31 14:05:51 -07006250 if (r.userId != userId) {
6251 throw new SecurityException("Calling requested user " + userId
6252 + " but app is user " + r.userId);
6253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254 }
6255
6256 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006257 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006258 boolean providerRunning = cpr != null;
6259 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006260 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006261 String msg;
6262 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6263 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 }
6265
6266 if (r != null && cpr.canRunHere(r)) {
6267 // This provider has been published or is in the process
6268 // of being published... but it is also allowed to run
6269 // in the caller's process, so don't make a connection
6270 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006271 ContentProviderHolder holder = cpr.newHolder(null);
6272 // don't give caller the provider object, it needs
6273 // to make its own.
6274 holder.provider = null;
6275 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 }
6277
6278 final long origId = Binder.clearCallingIdentity();
6279
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006280 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006282 conn = incProviderCountLocked(r, cpr, token, stable);
6283 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006284 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006285 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006286 // make sure to count it as being accessed and thus
6287 // back up on the LRU list. This is good because
6288 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006289 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006290 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006291 }
6292
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006293 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006294 if (false) {
6295 if (cpr.name.flattenToShortString().equals(
6296 "com.android.providers.calendar/.CalendarProvider2")) {
6297 Slog.v(TAG, "****************** KILLING "
6298 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006299 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006300 }
6301 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006302 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006303 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6304 // NOTE: there is still a race here where a signal could be
6305 // pending on the process even though we managed to update its
6306 // adj level. Not sure what to do about this, but at least
6307 // the race is now smaller.
6308 if (!success) {
6309 // Uh oh... it looks like the provider's process
6310 // has been killed on us. We need to wait for a new
6311 // process to be started, and make sure its death
6312 // doesn't kill our process.
6313 Slog.i(TAG,
6314 "Existing provider " + cpr.name.flattenToShortString()
6315 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006316 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006317 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006318 if (!lastRef) {
6319 // This wasn't the last ref our process had on
6320 // the provider... we have now been killed, bail.
6321 return null;
6322 }
6323 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006324 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006326 }
6327
6328 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006331 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006332 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006334 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006335 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006336 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006337 } catch (RemoteException ex) {
6338 }
6339 if (cpi == null) {
6340 return null;
6341 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006342 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6343 cpi.name, cpi.flags);
6344 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006345 userId = 0;
6346 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006347 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006348
Dianne Hackbornb424b632010-08-18 15:59:05 -07006349 String msg;
6350 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6351 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006352 }
6353
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006354 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006355 && !cpi.processName.equals("system")) {
6356 // If this content provider does not run in the system
6357 // process, and the system is not yet ready to run other
6358 // processes, then fail fast instead of hanging.
6359 throw new IllegalArgumentException(
6360 "Attempt to launch content provider before system ready");
6361 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006362
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006363 // Make sure that the user who owns this provider is started. If not,
6364 // we don't want to allow it to run.
6365 if (mStartedUsers.get(userId) == null) {
6366 Slog.w(TAG, "Unable to launch app "
6367 + cpi.applicationInfo.packageName + "/"
6368 + cpi.applicationInfo.uid + " for provider "
6369 + name + ": user " + userId + " is stopped");
6370 return null;
6371 }
6372
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006373 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006374 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375 final boolean firstClass = cpr == null;
6376 if (firstClass) {
6377 try {
6378 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006379 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006380 getApplicationInfo(
6381 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006382 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006384 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 + cpi.name);
6386 return null;
6387 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006388 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006389 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 } catch (RemoteException ex) {
6391 // pm is in same process, this will never happen.
6392 }
6393 }
6394
6395 if (r != null && cpr.canRunHere(r)) {
6396 // If this is a multiprocess provider, then just return its
6397 // info and allow the caller to instantiate it. Only do
6398 // this if the provider is the same user as the caller's
6399 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006400 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 }
6402
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006403 if (DEBUG_PROVIDER) {
6404 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006405 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006406 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 }
6408
6409 // This is single process, and our app is now connecting to it.
6410 // See if we are already in the process of launching this
6411 // provider.
6412 final int N = mLaunchingProviders.size();
6413 int i;
6414 for (i=0; i<N; i++) {
6415 if (mLaunchingProviders.get(i) == cpr) {
6416 break;
6417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 }
6419
6420 // If the provider is not already being launched, then get it
6421 // started.
6422 if (i >= N) {
6423 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006424
6425 try {
6426 // Content provider is now in use, its package can't be stopped.
6427 try {
6428 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006429 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006430 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006431 } catch (IllegalArgumentException e) {
6432 Slog.w(TAG, "Failed trying to unstop package "
6433 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006434 }
6435
6436 ProcessRecord proc = startProcessLocked(cpi.processName,
6437 cpr.appInfo, false, 0, "content provider",
6438 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006439 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006440 if (proc == null) {
6441 Slog.w(TAG, "Unable to launch app "
6442 + cpi.applicationInfo.packageName + "/"
6443 + cpi.applicationInfo.uid + " for provider "
6444 + name + ": process is bad");
6445 return null;
6446 }
6447 cpr.launchingApp = proc;
6448 mLaunchingProviders.add(cpr);
6449 } finally {
6450 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 }
6453
6454 // Make sure the provider is published (the same provider class
6455 // may be published under multiple names).
6456 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006457 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006459
Amith Yamasani742a6712011-05-04 14:49:28 -07006460 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006461 conn = incProviderCountLocked(r, cpr, token, stable);
6462 if (conn != null) {
6463 conn.waiting = true;
6464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006465 }
6466 }
6467
6468 // Wait for the provider to be published...
6469 synchronized (cpr) {
6470 while (cpr.provider == null) {
6471 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006472 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 + cpi.applicationInfo.packageName + "/"
6474 + cpi.applicationInfo.uid + " for provider "
6475 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006476 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 cpi.applicationInfo.packageName,
6478 cpi.applicationInfo.uid, name);
6479 return null;
6480 }
6481 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006482 if (DEBUG_MU) {
6483 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6484 + cpr.launchingApp);
6485 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006486 if (conn != null) {
6487 conn.waiting = true;
6488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 cpr.wait();
6490 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006491 } finally {
6492 if (conn != null) {
6493 conn.waiting = false;
6494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 }
6496 }
6497 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006498 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 }
6500
6501 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006502 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006503 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006504 if (caller == null) {
6505 String msg = "null IApplicationThread when getting content provider "
6506 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006507 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 throw new SecurityException(msg);
6509 }
6510
Dianne Hackborn41203752012-08-31 14:05:51 -07006511 return getContentProviderImpl(caller, name, null, stable,
6512 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 }
6514
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006515 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6516 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6517 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006518 return getContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006519 }
6520
Dianne Hackborn41203752012-08-31 14:05:51 -07006521 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6522 IBinder token, int userId) {
6523 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 }
6525
6526 /**
6527 * Drop a content provider from a ProcessRecord's bookkeeping
6528 * @param cpr
6529 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006530 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006531 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006533 ContentProviderConnection conn;
6534 try {
6535 conn = (ContentProviderConnection)connection;
6536 } catch (ClassCastException e) {
6537 String msg ="removeContentProvider: " + connection
6538 + " not a ContentProviderConnection";
6539 Slog.w(TAG, msg);
6540 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006542 if (conn == null) {
6543 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006545 if (decProviderCountLocked(conn, null, null, stable)) {
6546 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 }
6549 }
6550
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006551 public void removeContentProviderExternal(String name, IBinder token) {
6552 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6553 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006554 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006555 }
6556
Dianne Hackborn41203752012-08-31 14:05:51 -07006557 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006558 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006559 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 if(cpr == null) {
6561 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006562 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006563 return;
6564 }
6565
6566 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006567 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006568 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006569 if (localCpr.hasExternalProcessHandles()) {
6570 if (localCpr.removeExternalProcessHandleLocked(token)) {
6571 updateOomAdjLocked();
6572 } else {
6573 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6574 + " with no external reference for token: "
6575 + token + ".");
6576 }
6577 } else {
6578 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6579 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 }
6582 }
6583
6584 public final void publishContentProviders(IApplicationThread caller,
6585 List<ContentProviderHolder> providers) {
6586 if (providers == null) {
6587 return;
6588 }
6589
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006590 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006591 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006592 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006593 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006594 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 if (r == null) {
6596 throw new SecurityException(
6597 "Unable to find app for caller " + caller
6598 + " (pid=" + Binder.getCallingPid()
6599 + ") when publishing content providers");
6600 }
6601
6602 final long origId = Binder.clearCallingIdentity();
6603
6604 final int N = providers.size();
6605 for (int i=0; i<N; i++) {
6606 ContentProviderHolder src = providers.get(i);
6607 if (src == null || src.info == null || src.provider == null) {
6608 continue;
6609 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006610 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006611 if (DEBUG_MU)
6612 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006614 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006615 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 String names[] = dst.info.authority.split(";");
6617 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006618 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006619 }
6620
6621 int NL = mLaunchingProviders.size();
6622 int j;
6623 for (j=0; j<NL; j++) {
6624 if (mLaunchingProviders.get(j) == dst) {
6625 mLaunchingProviders.remove(j);
6626 j--;
6627 NL--;
6628 }
6629 }
6630 synchronized (dst) {
6631 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006632 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 dst.notifyAll();
6634 }
6635 updateOomAdjLocked(r);
6636 }
6637 }
6638
6639 Binder.restoreCallingIdentity(origId);
6640 }
6641 }
6642
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006643 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6644 ContentProviderConnection conn;
6645 try {
6646 conn = (ContentProviderConnection)connection;
6647 } catch (ClassCastException e) {
6648 String msg ="refContentProvider: " + connection
6649 + " not a ContentProviderConnection";
6650 Slog.w(TAG, msg);
6651 throw new IllegalArgumentException(msg);
6652 }
6653 if (conn == null) {
6654 throw new NullPointerException("connection is null");
6655 }
6656
6657 synchronized (this) {
6658 if (stable > 0) {
6659 conn.numStableIncs += stable;
6660 }
6661 stable = conn.stableCount + stable;
6662 if (stable < 0) {
6663 throw new IllegalStateException("stableCount < 0: " + stable);
6664 }
6665
6666 if (unstable > 0) {
6667 conn.numUnstableIncs += unstable;
6668 }
6669 unstable = conn.unstableCount + unstable;
6670 if (unstable < 0) {
6671 throw new IllegalStateException("unstableCount < 0: " + unstable);
6672 }
6673
6674 if ((stable+unstable) <= 0) {
6675 throw new IllegalStateException("ref counts can't go to zero here: stable="
6676 + stable + " unstable=" + unstable);
6677 }
6678 conn.stableCount = stable;
6679 conn.unstableCount = unstable;
6680 return !conn.dead;
6681 }
6682 }
6683
6684 public void unstableProviderDied(IBinder connection) {
6685 ContentProviderConnection conn;
6686 try {
6687 conn = (ContentProviderConnection)connection;
6688 } catch (ClassCastException e) {
6689 String msg ="refContentProvider: " + connection
6690 + " not a ContentProviderConnection";
6691 Slog.w(TAG, msg);
6692 throw new IllegalArgumentException(msg);
6693 }
6694 if (conn == null) {
6695 throw new NullPointerException("connection is null");
6696 }
6697
6698 // Safely retrieve the content provider associated with the connection.
6699 IContentProvider provider;
6700 synchronized (this) {
6701 provider = conn.provider.provider;
6702 }
6703
6704 if (provider == null) {
6705 // Um, yeah, we're way ahead of you.
6706 return;
6707 }
6708
6709 // Make sure the caller is being honest with us.
6710 if (provider.asBinder().pingBinder()) {
6711 // Er, no, still looks good to us.
6712 synchronized (this) {
6713 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6714 + " says " + conn + " died, but we don't agree");
6715 return;
6716 }
6717 }
6718
6719 // Well look at that! It's dead!
6720 synchronized (this) {
6721 if (conn.provider.provider != provider) {
6722 // But something changed... good enough.
6723 return;
6724 }
6725
6726 ProcessRecord proc = conn.provider.proc;
6727 if (proc == null || proc.thread == null) {
6728 // Seems like the process is already cleaned up.
6729 return;
6730 }
6731
6732 // As far as we're concerned, this is just like receiving a
6733 // death notification... just a bit prematurely.
6734 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6735 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006736 final long ident = Binder.clearCallingIdentity();
6737 try {
6738 appDiedLocked(proc, proc.pid, proc.thread);
6739 } finally {
6740 Binder.restoreCallingIdentity(ident);
6741 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006742 }
6743 }
6744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006746 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006747 synchronized (mSelf) {
6748 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6749 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006750 if (providers != null) {
6751 for (int i=providers.size()-1; i>=0; i--) {
6752 ProviderInfo pi = (ProviderInfo)providers.get(i);
6753 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6754 Slog.w(TAG, "Not installing system proc provider " + pi.name
6755 + ": not system .apk");
6756 providers.remove(i);
6757 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006758 }
6759 }
6760 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006761 if (providers != null) {
6762 mSystemThread.installSystemProviders(providers);
6763 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006764
6765 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006766
6767 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 }
6769
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006770 /**
6771 * Allows app to retrieve the MIME type of a URI without having permission
6772 * to access its content provider.
6773 *
6774 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6775 *
6776 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6777 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6778 */
6779 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006780 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006781 final String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07006782 final int userId = UserHandle.getCallingUserId();
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006783 final long ident = Binder.clearCallingIdentity();
6784 ContentProviderHolder holder = null;
6785
6786 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006787 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006788 if (holder != null) {
6789 return holder.provider.getType(uri);
6790 }
6791 } catch (RemoteException e) {
6792 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6793 return null;
6794 } finally {
6795 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006796 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006797 }
6798 Binder.restoreCallingIdentity(ident);
6799 }
6800
6801 return null;
6802 }
6803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006804 // =========================================================
6805 // GLOBAL MANAGEMENT
6806 // =========================================================
6807
6808 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006809 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006810 String proc = customProcess != null ? customProcess : info.processName;
6811 BatteryStatsImpl.Uid.Proc ps = null;
6812 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006813 int uid = info.uid;
6814 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006815 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006816 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6817 uid = 0;
6818 while (true) {
6819 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6820 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6821 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6822 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006823 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006824 mNextIsolatedProcessUid++;
6825 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6826 // No process for this uid, use it.
6827 break;
6828 }
6829 stepsLeft--;
6830 if (stepsLeft <= 0) {
6831 return null;
6832 }
6833 }
6834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006835 synchronized (stats) {
6836 ps = stats.getProcessStatsLocked(info.uid, proc);
6837 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006838 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 }
6840
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006841 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6842 ProcessRecord app;
6843 if (!isolated) {
6844 app = getProcessRecordLocked(info.processName, info.uid);
6845 } else {
6846 app = null;
6847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006848
6849 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006850 app = newProcessRecordLocked(null, info, null, isolated);
6851 mProcessNames.put(info.processName, app.uid, app);
6852 if (isolated) {
6853 mIsolatedProcesses.put(app.uid, app);
6854 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006855 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006856 }
6857
Dianne Hackborne7f97212011-02-24 14:40:20 -08006858 // This package really, really can not be stopped.
6859 try {
6860 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006861 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006862 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006863 } catch (IllegalArgumentException e) {
6864 Slog.w(TAG, "Failed trying to unstop package "
6865 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006866 }
6867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006868 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6869 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6870 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006871 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006872 }
6873 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6874 mPersistentStartingProcesses.add(app);
6875 startProcessLocked(app, "added application", app.processName);
6876 }
6877
6878 return app;
6879 }
6880
6881 public void unhandledBack() {
6882 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6883 "unhandledBack()");
6884
6885 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006886 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006887 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006888 TAG, "Performing unhandledBack(): stack size = " + count);
6889 if (count > 1) {
6890 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006891 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006892 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6893 Binder.restoreCallingIdentity(origId);
6894 }
6895 }
6896 }
6897
6898 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006899 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07006900 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006901 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07006902 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 ParcelFileDescriptor pfd = null;
6904 if (cph != null) {
6905 // We record the binder invoker's uid in thread-local storage before
6906 // going to the content provider to open the file. Later, in the code
6907 // that handles all permissions checks, we look for this uid and use
6908 // that rather than the Activity Manager's own uid. The effect is that
6909 // we do the check against the caller's permissions even though it looks
6910 // to the content provider like the Activity Manager itself is making
6911 // the request.
6912 sCallerIdentity.set(new Identity(
6913 Binder.getCallingPid(), Binder.getCallingUid()));
6914 try {
6915 pfd = cph.provider.openFile(uri, "r");
6916 } catch (FileNotFoundException e) {
6917 // do nothing; pfd will be returned null
6918 } finally {
6919 // Ensure that whatever happens, we clean up the identity state
6920 sCallerIdentity.remove();
6921 }
6922
6923 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07006924 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006925 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006926 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006927 }
6928 return pfd;
6929 }
6930
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006931 // Actually is sleeping or shutting down or whatever else in the future
6932 // is an inactive state.
6933 public boolean isSleeping() {
6934 return mSleeping || mShuttingDown;
6935 }
6936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006937 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006938 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6939 != PackageManager.PERMISSION_GRANTED) {
6940 throw new SecurityException("Requires permission "
6941 + android.Manifest.permission.DEVICE_POWER);
6942 }
6943
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006944 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006945 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006946 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006948 if (!mSleeping) {
6949 mSleeping = true;
6950 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006951
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006952 // Initialize the wake times of all processes.
6953 checkExcessivePowerUsageLocked(false);
6954 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6955 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6956 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958 }
6959 }
6960
Dianne Hackborn55280a92009-05-07 15:53:46 -07006961 public boolean shutdown(int timeout) {
6962 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6963 != PackageManager.PERMISSION_GRANTED) {
6964 throw new SecurityException("Requires permission "
6965 + android.Manifest.permission.SHUTDOWN);
6966 }
6967
6968 boolean timedout = false;
6969
6970 synchronized(this) {
6971 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006972 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006973
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006974 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006975 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006976 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006977 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006978 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006979 long delay = endTime - System.currentTimeMillis();
6980 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006981 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006982 timedout = true;
6983 break;
6984 }
6985 try {
6986 this.wait();
6987 } catch (InterruptedException e) {
6988 }
6989 }
6990 }
6991 }
6992
6993 mUsageStatsService.shutdown();
6994 mBatteryStatsService.shutdown();
6995
6996 return timedout;
6997 }
6998
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006999 public final void activitySlept(IBinder token) {
7000 if (localLOGV) Slog.v(
7001 TAG, "Activity slept: token=" + token);
7002
7003 ActivityRecord r = null;
7004
7005 final long origId = Binder.clearCallingIdentity();
7006
7007 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007008 r = mMainStack.isInStackLocked(token);
7009 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007010 mMainStack.activitySleptLocked(r);
7011 }
7012 }
7013
7014 Binder.restoreCallingIdentity(origId);
7015 }
7016
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007017 private void comeOutOfSleepIfNeededLocked() {
7018 if (!mWentToSleep && !mLockScreenShown) {
7019 if (mSleeping) {
7020 mSleeping = false;
7021 mMainStack.awakeFromSleepingLocked();
7022 mMainStack.resumeTopActivityLocked(null);
7023 }
7024 }
7025 }
7026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007028 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7029 != PackageManager.PERMISSION_GRANTED) {
7030 throw new SecurityException("Requires permission "
7031 + android.Manifest.permission.DEVICE_POWER);
7032 }
7033
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007034 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007035 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007036 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007037 comeOutOfSleepIfNeededLocked();
7038 }
7039 }
7040
Jeff Brownc042ee22012-05-08 13:03:42 -07007041 private void updateEventDispatchingLocked() {
7042 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7043 }
7044
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007045 public void setLockScreenShown(boolean shown) {
7046 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7047 != PackageManager.PERMISSION_GRANTED) {
7048 throw new SecurityException("Requires permission "
7049 + android.Manifest.permission.DEVICE_POWER);
7050 }
7051
7052 synchronized(this) {
7053 mLockScreenShown = shown;
7054 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007055 }
7056 }
7057
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007058 public void stopAppSwitches() {
7059 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7060 != PackageManager.PERMISSION_GRANTED) {
7061 throw new SecurityException("Requires permission "
7062 + android.Manifest.permission.STOP_APP_SWITCHES);
7063 }
7064
7065 synchronized(this) {
7066 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7067 + APP_SWITCH_DELAY_TIME;
7068 mDidAppSwitch = false;
7069 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7070 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7071 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7072 }
7073 }
7074
7075 public void resumeAppSwitches() {
7076 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7077 != PackageManager.PERMISSION_GRANTED) {
7078 throw new SecurityException("Requires permission "
7079 + android.Manifest.permission.STOP_APP_SWITCHES);
7080 }
7081
7082 synchronized(this) {
7083 // Note that we don't execute any pending app switches... we will
7084 // let those wait until either the timeout, or the next start
7085 // activity request.
7086 mAppSwitchesAllowedTime = 0;
7087 }
7088 }
7089
7090 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7091 String name) {
7092 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7093 return true;
7094 }
7095
7096 final int perm = checkComponentPermission(
7097 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007098 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007099 if (perm == PackageManager.PERMISSION_GRANTED) {
7100 return true;
7101 }
7102
Joe Onorato8a9b2202010-02-26 18:56:32 -08007103 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007104 return false;
7105 }
7106
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007107 public void setDebugApp(String packageName, boolean waitForDebugger,
7108 boolean persistent) {
7109 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7110 "setDebugApp()");
7111
7112 // Note that this is not really thread safe if there are multiple
7113 // callers into it at the same time, but that's not a situation we
7114 // care about.
7115 if (persistent) {
7116 final ContentResolver resolver = mContext.getContentResolver();
7117 Settings.System.putString(
7118 resolver, Settings.System.DEBUG_APP,
7119 packageName);
7120 Settings.System.putInt(
7121 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7122 waitForDebugger ? 1 : 0);
7123 }
7124
7125 synchronized (this) {
7126 if (!persistent) {
7127 mOrigDebugApp = mDebugApp;
7128 mOrigWaitForDebugger = mWaitForDebugger;
7129 }
7130 mDebugApp = packageName;
7131 mWaitForDebugger = waitForDebugger;
7132 mDebugTransient = !persistent;
7133 if (packageName != null) {
7134 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07007135 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007136 Binder.restoreCallingIdentity(origId);
7137 }
7138 }
7139 }
7140
Siva Velusamy92a8b222012-03-09 16:24:04 -08007141 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7142 synchronized (this) {
7143 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7144 if (!isDebuggable) {
7145 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7146 throw new SecurityException("Process not debuggable: " + app.packageName);
7147 }
7148 }
7149
7150 mOpenGlTraceApp = processName;
7151 }
7152 }
7153
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007154 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7155 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7156 synchronized (this) {
7157 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7158 if (!isDebuggable) {
7159 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7160 throw new SecurityException("Process not debuggable: " + app.packageName);
7161 }
7162 }
7163 mProfileApp = processName;
7164 mProfileFile = profileFile;
7165 if (mProfileFd != null) {
7166 try {
7167 mProfileFd.close();
7168 } catch (IOException e) {
7169 }
7170 mProfileFd = null;
7171 }
7172 mProfileFd = profileFd;
7173 mProfileType = 0;
7174 mAutoStopProfiler = autoStopProfiler;
7175 }
7176 }
7177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 public void setAlwaysFinish(boolean enabled) {
7179 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7180 "setAlwaysFinish()");
7181
7182 Settings.System.putInt(
7183 mContext.getContentResolver(),
7184 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7185
7186 synchronized (this) {
7187 mAlwaysFinishActivities = enabled;
7188 }
7189 }
7190
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007191 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007192 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007193 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007194 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007195 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 }
7197 }
7198
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007199 public boolean isUserAMonkey() {
7200 // For now the fact that there is a controller implies
7201 // we have a monkey.
7202 synchronized (this) {
7203 return mController != null;
7204 }
7205 }
7206
Jeff Sharkeya4620792011-05-20 15:29:23 -07007207 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007208 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7209 "registerProcessObserver()");
7210 synchronized (this) {
7211 mProcessObservers.register(observer);
7212 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007213 }
7214
7215 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007216 synchronized (this) {
7217 mProcessObservers.unregister(observer);
7218 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007219 }
7220
Daniel Sandler69a48172010-06-23 16:29:36 -04007221 public void setImmersive(IBinder token, boolean immersive) {
7222 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007223 ActivityRecord r = mMainStack.isInStackLocked(token);
7224 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007225 throw new IllegalArgumentException();
7226 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007227 r.immersive = immersive;
7228 }
7229 }
7230
7231 public boolean isImmersive(IBinder token) {
7232 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007233 ActivityRecord r = mMainStack.isInStackLocked(token);
7234 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007235 throw new IllegalArgumentException();
7236 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007237 return r.immersive;
7238 }
7239 }
7240
7241 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007242 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007243 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007244 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007245 return (r != null) ? r.immersive : false;
7246 }
7247 }
7248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007249 public final void enterSafeMode() {
7250 synchronized(this) {
7251 // It only makes sense to do this before the system is ready
7252 // and started launching other packages.
7253 if (!mSystemReady) {
7254 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007255 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007256 } catch (RemoteException e) {
7257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007258 }
7259 }
7260 }
7261
Jeff Brownb09abc12011-01-13 21:08:27 -08007262 public final void showSafeModeOverlay() {
7263 View v = LayoutInflater.from(mContext).inflate(
7264 com.android.internal.R.layout.safe_mode, null);
7265 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7266 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7267 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7268 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007269 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007270 lp.format = v.getBackground().getOpacity();
7271 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7272 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7273 ((WindowManager)mContext.getSystemService(
7274 Context.WINDOW_SERVICE)).addView(v, lp);
7275 }
7276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007277 public void noteWakeupAlarm(IIntentSender sender) {
7278 if (!(sender instanceof PendingIntentRecord)) {
7279 return;
7280 }
7281 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7282 synchronized (stats) {
7283 if (mBatteryStatsService.isOnBattery()) {
7284 mBatteryStatsService.enforceCallingPermission();
7285 PendingIntentRecord rec = (PendingIntentRecord)sender;
7286 int MY_UID = Binder.getCallingUid();
7287 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7288 BatteryStatsImpl.Uid.Pkg pkg =
7289 stats.getPackageStatsLocked(uid, rec.key.packageName);
7290 pkg.incWakeupsLocked();
7291 }
7292 }
7293 }
7294
Dianne Hackborn64825172011-03-02 21:32:58 -08007295 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007297 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007298 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007299 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007300 // XXX Note: don't acquire main activity lock here, because the window
7301 // manager calls in with its locks held.
7302
7303 boolean killed = false;
7304 synchronized (mPidsSelfLocked) {
7305 int[] types = new int[pids.length];
7306 int worstType = 0;
7307 for (int i=0; i<pids.length; i++) {
7308 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7309 if (proc != null) {
7310 int type = proc.setAdj;
7311 types[i] = type;
7312 if (type > worstType) {
7313 worstType = type;
7314 }
7315 }
7316 }
7317
Dianne Hackborn64825172011-03-02 21:32:58 -08007318 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007319 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007320 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7321 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007322 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007323 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007324
7325 // If this is not a secure call, don't let it kill processes that
7326 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007327 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7328 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007329 }
7330
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007331 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007332 for (int i=0; i<pids.length; i++) {
7333 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7334 if (proc == null) {
7335 continue;
7336 }
7337 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007338 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007339 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007340 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7341 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007343 proc.killedBackground = true;
7344 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007345 }
7346 }
7347 }
7348 return killed;
7349 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007350
7351 @Override
7352 public boolean killProcessesBelowForeground(String reason) {
7353 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7354 throw new SecurityException("killProcessesBelowForeground() only available to system");
7355 }
7356
7357 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7358 }
7359
7360 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7361 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7362 throw new SecurityException("killProcessesBelowAdj() only available to system");
7363 }
7364
7365 boolean killed = false;
7366 synchronized (mPidsSelfLocked) {
7367 final int size = mPidsSelfLocked.size();
7368 for (int i = 0; i < size; i++) {
7369 final int pid = mPidsSelfLocked.keyAt(i);
7370 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7371 if (proc == null) continue;
7372
7373 final int adj = proc.setAdj;
7374 if (adj > belowAdj && !proc.killedBackground) {
7375 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7376 EventLog.writeEvent(
7377 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7378 killed = true;
7379 proc.killedBackground = true;
7380 Process.killProcessQuiet(pid);
7381 }
7382 }
7383 }
7384 return killed;
7385 }
7386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007387 public final void startRunning(String pkg, String cls, String action,
7388 String data) {
7389 synchronized(this) {
7390 if (mStartRunning) {
7391 return;
7392 }
7393 mStartRunning = true;
7394 mTopComponent = pkg != null && cls != null
7395 ? new ComponentName(pkg, cls) : null;
7396 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7397 mTopData = data;
7398 if (!mSystemReady) {
7399 return;
7400 }
7401 }
7402
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007403 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007404 }
7405
7406 private void retrieveSettings() {
7407 final ContentResolver resolver = mContext.getContentResolver();
7408 String debugApp = Settings.System.getString(
7409 resolver, Settings.System.DEBUG_APP);
7410 boolean waitForDebugger = Settings.System.getInt(
7411 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7412 boolean alwaysFinishActivities = Settings.System.getInt(
7413 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7414
7415 Configuration configuration = new Configuration();
7416 Settings.System.getConfiguration(resolver, configuration);
7417
7418 synchronized (this) {
7419 mDebugApp = mOrigDebugApp = debugApp;
7420 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7421 mAlwaysFinishActivities = alwaysFinishActivities;
7422 // This happens before any activities are started, so we can
7423 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007424 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007425 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007426 }
7427 }
7428
7429 public boolean testIsSystemReady() {
7430 // no need to synchronize(this) just to read & return the value
7431 return mSystemReady;
7432 }
7433
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007434 private static File getCalledPreBootReceiversFile() {
7435 File dataDir = Environment.getDataDirectory();
7436 File systemDir = new File(dataDir, "system");
7437 File fname = new File(systemDir, "called_pre_boots.dat");
7438 return fname;
7439 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007440
7441 static final int LAST_DONE_VERSION = 10000;
7442
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007443 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7444 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7445 File file = getCalledPreBootReceiversFile();
7446 FileInputStream fis = null;
7447 try {
7448 fis = new FileInputStream(file);
7449 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007450 int fvers = dis.readInt();
7451 if (fvers == LAST_DONE_VERSION) {
7452 String vers = dis.readUTF();
7453 String codename = dis.readUTF();
7454 String build = dis.readUTF();
7455 if (android.os.Build.VERSION.RELEASE.equals(vers)
7456 && android.os.Build.VERSION.CODENAME.equals(codename)
7457 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7458 int num = dis.readInt();
7459 while (num > 0) {
7460 num--;
7461 String pkg = dis.readUTF();
7462 String cls = dis.readUTF();
7463 lastDoneReceivers.add(new ComponentName(pkg, cls));
7464 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007465 }
7466 }
7467 } catch (FileNotFoundException e) {
7468 } catch (IOException e) {
7469 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7470 } finally {
7471 if (fis != null) {
7472 try {
7473 fis.close();
7474 } catch (IOException e) {
7475 }
7476 }
7477 }
7478 return lastDoneReceivers;
7479 }
7480
7481 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7482 File file = getCalledPreBootReceiversFile();
7483 FileOutputStream fos = null;
7484 DataOutputStream dos = null;
7485 try {
7486 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7487 fos = new FileOutputStream(file);
7488 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007489 dos.writeInt(LAST_DONE_VERSION);
7490 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007491 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007492 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007493 dos.writeInt(list.size());
7494 for (int i=0; i<list.size(); i++) {
7495 dos.writeUTF(list.get(i).getPackageName());
7496 dos.writeUTF(list.get(i).getClassName());
7497 }
7498 } catch (IOException e) {
7499 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7500 file.delete();
7501 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007502 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007503 if (dos != null) {
7504 try {
7505 dos.close();
7506 } catch (IOException e) {
7507 // TODO Auto-generated catch block
7508 e.printStackTrace();
7509 }
7510 }
7511 }
7512 }
7513
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007514 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007515 synchronized(this) {
7516 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007517 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007518 return;
7519 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007520
7521 // Check to see if there are any update receivers to run.
7522 if (!mDidUpdate) {
7523 if (mWaitingUpdate) {
7524 return;
7525 }
7526 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7527 List<ResolveInfo> ris = null;
7528 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007529 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007530 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007531 } catch (RemoteException e) {
7532 }
7533 if (ris != null) {
7534 for (int i=ris.size()-1; i>=0; i--) {
7535 if ((ris.get(i).activityInfo.applicationInfo.flags
7536 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7537 ris.remove(i);
7538 }
7539 }
7540 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007541
7542 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7543
7544 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007545 for (int i=0; i<ris.size(); i++) {
7546 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007547 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7548 if (lastDoneReceivers.contains(comp)) {
7549 ris.remove(i);
7550 i--;
7551 }
7552 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007553
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007554 for (int i=0; i<ris.size(); i++) {
7555 ActivityInfo ai = ris.get(i).activityInfo;
7556 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7557 doneReceivers.add(comp);
7558 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007559 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007560 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007561 finisher = new IIntentReceiver.Stub() {
7562 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007563 String data, Bundle extras, boolean ordered,
Dianne Hackborn20e80982012-08-31 19:00:44 -07007564 boolean sticky, int sendingUser) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007565 // The raw IIntentReceiver interface is called
7566 // with the AM lock held, so redispatch to
7567 // execute our code without the lock.
7568 mHandler.post(new Runnable() {
7569 public void run() {
7570 synchronized (ActivityManagerService.this) {
7571 mDidUpdate = true;
7572 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007573 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007574 showBootMessage(mContext.getText(
7575 R.string.android_upgrading_complete),
7576 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007577 systemReady(goingCallback);
7578 }
7579 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007580 }
7581 };
7582 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007583 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007584 // XXX also need to send this to stopped users(!!!)
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007585 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007586 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007587 UserHandle.USER_ALL);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007588 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007589 mWaitingUpdate = true;
7590 }
7591 }
7592 }
7593 if (mWaitingUpdate) {
7594 return;
7595 }
7596 mDidUpdate = true;
7597 }
7598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007599 mSystemReady = true;
7600 if (!mStartRunning) {
7601 return;
7602 }
7603 }
7604
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007605 ArrayList<ProcessRecord> procsToKill = null;
7606 synchronized(mPidsSelfLocked) {
7607 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7608 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7609 if (!isAllowedWhileBooting(proc.info)){
7610 if (procsToKill == null) {
7611 procsToKill = new ArrayList<ProcessRecord>();
7612 }
7613 procsToKill.add(proc);
7614 }
7615 }
7616 }
7617
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007618 synchronized(this) {
7619 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007620 for (int i=procsToKill.size()-1; i>=0; i--) {
7621 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007622 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007623 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007624 }
7625 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007626
7627 // Now that we have cleaned up any update processes, we
7628 // are ready to start launching real processes and know that
7629 // we won't trample on them any more.
7630 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007631 }
7632
Joe Onorato8a9b2202010-02-26 18:56:32 -08007633 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007634 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007635 SystemClock.uptimeMillis());
7636
7637 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007638 // Make sure we have no pre-ready processes sitting around.
7639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007640 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7641 ResolveInfo ri = mContext.getPackageManager()
7642 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007643 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007644 CharSequence errorMsg = null;
7645 if (ri != null) {
7646 ActivityInfo ai = ri.activityInfo;
7647 ApplicationInfo app = ai.applicationInfo;
7648 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7649 mTopAction = Intent.ACTION_FACTORY_TEST;
7650 mTopData = null;
7651 mTopComponent = new ComponentName(app.packageName,
7652 ai.name);
7653 } else {
7654 errorMsg = mContext.getResources().getText(
7655 com.android.internal.R.string.factorytest_not_system);
7656 }
7657 } else {
7658 errorMsg = mContext.getResources().getText(
7659 com.android.internal.R.string.factorytest_no_action);
7660 }
7661 if (errorMsg != null) {
7662 mTopAction = null;
7663 mTopData = null;
7664 mTopComponent = null;
7665 Message msg = Message.obtain();
7666 msg.what = SHOW_FACTORY_ERROR_MSG;
7667 msg.getData().putCharSequence("msg", errorMsg);
7668 mHandler.sendMessage(msg);
7669 }
7670 }
7671 }
7672
7673 retrieveSettings();
7674
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007675 if (goingCallback != null) goingCallback.run();
7676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007677 synchronized (this) {
7678 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7679 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007680 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007681 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007682 if (apps != null) {
7683 int N = apps.size();
7684 int i;
7685 for (i=0; i<N; i++) {
7686 ApplicationInfo info
7687 = (ApplicationInfo)apps.get(i);
7688 if (info != null &&
7689 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007690 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007691 }
7692 }
7693 }
7694 } catch (RemoteException ex) {
7695 // pm is in same process, this will never happen.
7696 }
7697 }
7698
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007699 // Start up initial activity.
7700 mBooting = true;
7701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007702 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007703 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007704 Message msg = Message.obtain();
7705 msg.what = SHOW_UID_ERROR_MSG;
7706 mHandler.sendMessage(msg);
7707 }
7708 } catch (RemoteException e) {
7709 }
7710
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007711 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 }
7713 }
7714
Dan Egnorb7f03672009-12-09 16:22:32 -08007715 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007716 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007717 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007718 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007719 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007720 startAppProblemLocked(app);
7721 app.stopFreezingAllLocked();
7722 return handleAppCrashLocked(app);
7723 }
7724
Dan Egnorb7f03672009-12-09 16:22:32 -08007725 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007726 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007727 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007728 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007729 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7730 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007731 startAppProblemLocked(app);
7732 app.stopFreezingAllLocked();
7733 }
7734
7735 /**
7736 * Generate a process error record, suitable for attachment to a ProcessRecord.
7737 *
7738 * @param app The ProcessRecord in which the error occurred.
7739 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7740 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007741 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007742 * @param shortMsg Short message describing the crash.
7743 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007744 * @param stackTrace Full crash stack trace, may be null.
7745 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007746 * @return Returns a fully-formed AppErrorStateInfo record.
7747 */
7748 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007749 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007750 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007752 report.condition = condition;
7753 report.processName = app.processName;
7754 report.pid = app.pid;
7755 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007756 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007757 report.shortMsg = shortMsg;
7758 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007759 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007760
7761 return report;
7762 }
7763
Dan Egnor42471dd2010-01-07 17:25:22 -08007764 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007765 synchronized (this) {
7766 app.crashing = false;
7767 app.crashingReport = null;
7768 app.notResponding = false;
7769 app.notRespondingReport = null;
7770 if (app.anrDialog == fromDialog) {
7771 app.anrDialog = null;
7772 }
7773 if (app.waitDialog == fromDialog) {
7774 app.waitDialog = null;
7775 }
7776 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007777 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007778 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007779 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7780 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007781 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 }
7784 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007785
Dan Egnorb7f03672009-12-09 16:22:32 -08007786 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007787 if (mHeadless) {
7788 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7789 return false;
7790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 long now = SystemClock.uptimeMillis();
7792
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007793 Long crashTime;
7794 if (!app.isolated) {
7795 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7796 } else {
7797 crashTime = null;
7798 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007799 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007801 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007802 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007803 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007804 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007805 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7806 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007808 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007810 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007811 }
7812 }
7813 if (!app.persistent) {
7814 // We don't want to start this process again until the user
7815 // explicitly does so... but for persistent process, we really
7816 // need to keep it running. If a persistent process is actually
7817 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007818 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007819 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007820 if (!app.isolated) {
7821 // XXX We don't have a way to mark isolated processes
7822 // as bad, since they don't have a peristent identity.
7823 mBadProcesses.put(app.info.processName, app.uid, now);
7824 mProcessCrashTimes.remove(app.info.processName, app.uid);
7825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007827 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007828 // Don't let services in this process be restarted and potentially
7829 // annoy the user repeatedly. Unless it is persistent, since those
7830 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007831 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007832 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007833 return false;
7834 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007835 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007836 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007837 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007838 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007839 // If the top running activity is from this crashing
7840 // process, then terminate it to avoid getting in a loop.
7841 Slog.w(TAG, " Force finishing activity "
7842 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007843 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007844 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007845 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007846 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007847 // stopped, to avoid a situation where one will get
7848 // re-start our crashing activity once it gets resumed again.
7849 index--;
7850 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007851 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007852 if (r.state == ActivityState.RESUMED
7853 || r.state == ActivityState.PAUSING
7854 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007855 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007856 Slog.w(TAG, " Force finishing activity "
7857 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007858 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007859 Activity.RESULT_CANCELED, null, "crashed");
7860 }
7861 }
7862 }
7863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 }
7865
7866 // Bump up the crash count of any services currently running in the proc.
7867 if (app.services.size() != 0) {
7868 // Any services running in the application need to be placed
7869 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007870 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007871 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007872 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007873 sr.crashCount++;
7874 }
7875 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007876
7877 // If the crashing process is what we consider to be the "home process" and it has been
7878 // replaced by a third-party app, clear the package preferred activities from packages
7879 // with a home activity running in the process to prevent a repeatedly crashing app
7880 // from blocking the user to manually clear the list.
7881 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7882 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7883 Iterator it = mHomeProcess.activities.iterator();
7884 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007885 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007886 if (r.isHomeActivity) {
7887 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7888 try {
7889 ActivityThread.getPackageManager()
7890 .clearPackagePreferredActivities(r.packageName);
7891 } catch (RemoteException c) {
7892 // pm is in same process, this will never happen.
7893 }
7894 }
7895 }
7896 }
7897
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007898 if (!app.isolated) {
7899 // XXX Can't keep track of crash times for isolated processes,
7900 // because they don't have a perisistent identity.
7901 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7902 }
7903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007904 return true;
7905 }
7906
7907 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007908 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7909 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007910 skipCurrentReceiverLocked(app);
7911 }
7912
7913 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007914 for (BroadcastQueue queue : mBroadcastQueues) {
7915 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 }
7917 }
7918
Dan Egnor60d87622009-12-16 16:32:58 -08007919 /**
7920 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7921 * The application process will exit immediately after this call returns.
7922 * @param app object of the crashing app, null for the system server
7923 * @param crashInfo describing the exception
7924 */
7925 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007926 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007927 final String processName = app == null ? "system_server"
7928 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007929
7930 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007931 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007932 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007933 crashInfo.exceptionClassName,
7934 crashInfo.exceptionMessage,
7935 crashInfo.throwFileName,
7936 crashInfo.throwLineNumber);
7937
Jeff Sharkeya353d262011-10-28 11:12:06 -07007938 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007939
7940 crashApplication(r, crashInfo);
7941 }
7942
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007943 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007944 IBinder app,
7945 int violationMask,
7946 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007947 ProcessRecord r = findAppProcess(app, "StrictMode");
7948 if (r == null) {
7949 return;
7950 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007951
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007952 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007953 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007954 boolean logIt = true;
7955 synchronized (mAlreadyLoggedViolatedStacks) {
7956 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7957 logIt = false;
7958 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007959 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007960 // the relative pain numbers, without logging all
7961 // the stack traces repeatedly. We'd want to do
7962 // likewise in the client code, which also does
7963 // dup suppression, before the Binder call.
7964 } else {
7965 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7966 mAlreadyLoggedViolatedStacks.clear();
7967 }
7968 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7969 }
7970 }
7971 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007972 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007973 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007974 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007975
7976 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7977 AppErrorResult result = new AppErrorResult();
7978 synchronized (this) {
7979 final long origId = Binder.clearCallingIdentity();
7980
7981 Message msg = Message.obtain();
7982 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7983 HashMap<String, Object> data = new HashMap<String, Object>();
7984 data.put("result", result);
7985 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007986 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007987 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007988 msg.obj = data;
7989 mHandler.sendMessage(msg);
7990
7991 Binder.restoreCallingIdentity(origId);
7992 }
7993 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007994 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007995 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007996 }
7997
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007998 // Depending on the policy in effect, there could be a bunch of
7999 // these in quick succession so we try to batch these together to
8000 // minimize disk writes, number of dropbox entries, and maximize
8001 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008002 private void logStrictModeViolationToDropBox(
8003 ProcessRecord process,
8004 StrictMode.ViolationInfo info) {
8005 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008006 return;
8007 }
8008 final boolean isSystemApp = process == null ||
8009 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8010 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008011 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008012 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8013 final DropBoxManager dbox = (DropBoxManager)
8014 mContext.getSystemService(Context.DROPBOX_SERVICE);
8015
8016 // Exit early if the dropbox isn't configured to accept this report type.
8017 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8018
8019 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008020 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008021 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8022 synchronized (sb) {
8023 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008024 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008025 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8026 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008027 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8028 if (info.violationNumThisLoop != 0) {
8029 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8030 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008031 if (info.numAnimationsRunning != 0) {
8032 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8033 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008034 if (info.broadcastIntentAction != null) {
8035 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8036 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008037 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008038 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008039 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008040 if (info.numInstances != -1) {
8041 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8042 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008043 if (info.tags != null) {
8044 for (String tag : info.tags) {
8045 sb.append("Span-Tag: ").append(tag).append("\n");
8046 }
8047 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008048 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008049 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8050 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008051 }
8052 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008053
8054 // Only buffer up to ~64k. Various logging bits truncate
8055 // things at 128k.
8056 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008057 }
8058
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008059 // Flush immediately if the buffer's grown too large, or this
8060 // is a non-system app. Non-system apps are isolated with a
8061 // different tag & policy and not batched.
8062 //
8063 // Batching is useful during internal testing with
8064 // StrictMode settings turned up high. Without batching,
8065 // thousands of separate files could be created on boot.
8066 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008067 new Thread("Error dump: " + dropboxTag) {
8068 @Override
8069 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008070 String report;
8071 synchronized (sb) {
8072 report = sb.toString();
8073 sb.delete(0, sb.length());
8074 sb.trimToSize();
8075 }
8076 if (report.length() != 0) {
8077 dbox.addText(dropboxTag, report);
8078 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008079 }
8080 }.start();
8081 return;
8082 }
8083
8084 // System app batching:
8085 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008086 // An existing dropbox-writing thread is outstanding, so
8087 // we don't need to start it up. The existing thread will
8088 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008089 return;
8090 }
8091
8092 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8093 // (After this point, we shouldn't access AMS internal data structures.)
8094 new Thread("Error dump: " + dropboxTag) {
8095 @Override
8096 public void run() {
8097 // 5 second sleep to let stacks arrive and be batched together
8098 try {
8099 Thread.sleep(5000); // 5 seconds
8100 } catch (InterruptedException e) {}
8101
8102 String errorReport;
8103 synchronized (mStrictModeBuffer) {
8104 errorReport = mStrictModeBuffer.toString();
8105 if (errorReport.length() == 0) {
8106 return;
8107 }
8108 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8109 mStrictModeBuffer.trimToSize();
8110 }
8111 dbox.addText(dropboxTag, errorReport);
8112 }
8113 }.start();
8114 }
8115
Dan Egnor60d87622009-12-16 16:32:58 -08008116 /**
8117 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8118 * @param app object of the crashing app, null for the system server
8119 * @param tag reported by the caller
8120 * @param crashInfo describing the context of the error
8121 * @return true if the process should exit immediately (WTF is fatal)
8122 */
8123 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008124 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008125 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008126 final String processName = app == null ? "system_server"
8127 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008128
8129 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008130 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008131 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008132 tag, crashInfo.exceptionMessage);
8133
Jeff Sharkeya353d262011-10-28 11:12:06 -07008134 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008135
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008136 if (r != null && r.pid != Process.myPid() &&
8137 Settings.Secure.getInt(mContext.getContentResolver(),
8138 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008139 crashApplication(r, crashInfo);
8140 return true;
8141 } else {
8142 return false;
8143 }
8144 }
8145
8146 /**
8147 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8148 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8149 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008150 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008151 if (app == null) {
8152 return null;
8153 }
8154
8155 synchronized (this) {
8156 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8157 final int NA = apps.size();
8158 for (int ia=0; ia<NA; ia++) {
8159 ProcessRecord p = apps.valueAt(ia);
8160 if (p.thread != null && p.thread.asBinder() == app) {
8161 return p;
8162 }
8163 }
8164 }
8165
Dianne Hackborncb44d962011-03-10 17:02:27 -08008166 Slog.w(TAG, "Can't find mystery application for " + reason
8167 + " from pid=" + Binder.getCallingPid()
8168 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008169 return null;
8170 }
8171 }
8172
8173 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008174 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8175 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008176 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008177 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8178 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008179 // Watchdog thread ends up invoking this function (with
8180 // a null ProcessRecord) to add the stack file to dropbox.
8181 // Do not acquire a lock on this (am) in such cases, as it
8182 // could cause a potential deadlock, if and when watchdog
8183 // is invoked due to unavailability of lock on am and it
8184 // would prevent watchdog from killing system_server.
8185 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008186 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008187 return;
8188 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008189 // Note: ProcessRecord 'process' is guarded by the service
8190 // instance. (notably process.pkgList, which could otherwise change
8191 // concurrently during execution of this method)
8192 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008193 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008194 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008195 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008196 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8197 for (String pkg : process.pkgList) {
8198 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008199 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008200 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008201 if (pi != null) {
8202 sb.append(" v").append(pi.versionCode);
8203 if (pi.versionName != null) {
8204 sb.append(" (").append(pi.versionName).append(")");
8205 }
8206 }
8207 } catch (RemoteException e) {
8208 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008209 }
Dan Egnora455d192010-03-12 08:52:28 -08008210 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008211 }
Dan Egnora455d192010-03-12 08:52:28 -08008212 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008213 }
8214
8215 private static String processClass(ProcessRecord process) {
8216 if (process == null || process.pid == MY_PID) {
8217 return "system_server";
8218 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8219 return "system_app";
8220 } else {
8221 return "data_app";
8222 }
8223 }
8224
8225 /**
8226 * Write a description of an error (crash, WTF, ANR) to the drop box.
8227 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8228 * @param process which caused the error, null means the system server
8229 * @param activity which triggered the error, null if unknown
8230 * @param parent activity related to the error, null if unknown
8231 * @param subject line related to the error, null if absent
8232 * @param report in long form describing the error, null if absent
8233 * @param logFile to include in the report, null if none
8234 * @param crashInfo giving an application stack trace, null if absent
8235 */
8236 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008237 ProcessRecord process, String processName, ActivityRecord activity,
8238 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008239 final String report, final File logFile,
8240 final ApplicationErrorReport.CrashInfo crashInfo) {
8241 // NOTE -- this must never acquire the ActivityManagerService lock,
8242 // otherwise the watchdog may be prevented from resetting the system.
8243
8244 final String dropboxTag = processClass(process) + "_" + eventType;
8245 final DropBoxManager dbox = (DropBoxManager)
8246 mContext.getSystemService(Context.DROPBOX_SERVICE);
8247
8248 // Exit early if the dropbox isn't configured to accept this report type.
8249 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8250
8251 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008252 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008253 if (activity != null) {
8254 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8255 }
8256 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8257 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8258 }
8259 if (parent != null && parent != activity) {
8260 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8261 }
8262 if (subject != null) {
8263 sb.append("Subject: ").append(subject).append("\n");
8264 }
8265 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008266 if (Debug.isDebuggerConnected()) {
8267 sb.append("Debugger: Connected\n");
8268 }
Dan Egnora455d192010-03-12 08:52:28 -08008269 sb.append("\n");
8270
8271 // Do the rest in a worker thread to avoid blocking the caller on I/O
8272 // (After this point, we shouldn't access AMS internal data structures.)
8273 Thread worker = new Thread("Error dump: " + dropboxTag) {
8274 @Override
8275 public void run() {
8276 if (report != null) {
8277 sb.append(report);
8278 }
8279 if (logFile != null) {
8280 try {
8281 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8282 } catch (IOException e) {
8283 Slog.e(TAG, "Error reading " + logFile, e);
8284 }
8285 }
8286 if (crashInfo != null && crashInfo.stackTrace != null) {
8287 sb.append(crashInfo.stackTrace);
8288 }
8289
8290 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8291 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8292 if (lines > 0) {
8293 sb.append("\n");
8294
8295 // Merge several logcat streams, and take the last N lines
8296 InputStreamReader input = null;
8297 try {
8298 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8299 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8300 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8301
8302 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8303 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8304 input = new InputStreamReader(logcat.getInputStream());
8305
8306 int num;
8307 char[] buf = new char[8192];
8308 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8309 } catch (IOException e) {
8310 Slog.e(TAG, "Error running logcat", e);
8311 } finally {
8312 if (input != null) try { input.close(); } catch (IOException e) {}
8313 }
8314 }
8315
8316 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008317 }
Dan Egnora455d192010-03-12 08:52:28 -08008318 };
8319
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008320 if (process == null) {
8321 // If process is null, we are being called from some internal code
8322 // and may be about to die -- run this synchronously.
8323 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008324 } else {
8325 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008326 }
8327 }
8328
8329 /**
8330 * Bring up the "unexpected error" dialog box for a crashing app.
8331 * Deal with edge cases (intercepts from instrumented applications,
8332 * ActivityController, error intent receivers, that sort of thing).
8333 * @param r the application crashing
8334 * @param crashInfo describing the failure
8335 */
8336 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008337 long timeMillis = System.currentTimeMillis();
8338 String shortMsg = crashInfo.exceptionClassName;
8339 String longMsg = crashInfo.exceptionMessage;
8340 String stackTrace = crashInfo.stackTrace;
8341 if (shortMsg != null && longMsg != null) {
8342 longMsg = shortMsg + ": " + longMsg;
8343 } else if (shortMsg != null) {
8344 longMsg = shortMsg;
8345 }
8346
Dan Egnor60d87622009-12-16 16:32:58 -08008347 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008348 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008349 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008350 try {
8351 String name = r != null ? r.processName : null;
8352 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008353 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008354 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008355 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008356 + " at watcher's request");
8357 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008358 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008359 }
8360 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008361 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008362 }
8363 }
8364
8365 final long origId = Binder.clearCallingIdentity();
8366
8367 // If this process is running instrumentation, finish it.
8368 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008369 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008370 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008371 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8372 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008373 Bundle info = new Bundle();
8374 info.putString("shortMsg", shortMsg);
8375 info.putString("longMsg", longMsg);
8376 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8377 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008378 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008379 }
8380
Dan Egnor60d87622009-12-16 16:32:58 -08008381 // If we can't identify the process or it's already exceeded its crash quota,
8382 // quit right away without showing a crash dialog.
8383 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008384 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008385 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008386 }
8387
8388 Message msg = Message.obtain();
8389 msg.what = SHOW_ERROR_MSG;
8390 HashMap data = new HashMap();
8391 data.put("result", result);
8392 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008393 msg.obj = data;
8394 mHandler.sendMessage(msg);
8395
8396 Binder.restoreCallingIdentity(origId);
8397 }
8398
8399 int res = result.get();
8400
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008401 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008402 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008403 if (r != null && !r.isolated) {
8404 // XXX Can't keep track of crash time for isolated processes,
8405 // since they don't have a persistent identity.
8406 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008407 SystemClock.uptimeMillis());
8408 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008409 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008410 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008411 }
8412 }
8413
8414 if (appErrorIntent != null) {
8415 try {
8416 mContext.startActivity(appErrorIntent);
8417 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008418 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008421 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008422
8423 Intent createAppErrorIntentLocked(ProcessRecord r,
8424 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8425 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008426 if (report == null) {
8427 return null;
8428 }
8429 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8430 result.setComponent(r.errorReportReceiver);
8431 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8432 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8433 return result;
8434 }
8435
Dan Egnorb7f03672009-12-09 16:22:32 -08008436 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8437 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008438 if (r.errorReportReceiver == null) {
8439 return null;
8440 }
8441
8442 if (!r.crashing && !r.notResponding) {
8443 return null;
8444 }
8445
Dan Egnorb7f03672009-12-09 16:22:32 -08008446 ApplicationErrorReport report = new ApplicationErrorReport();
8447 report.packageName = r.info.packageName;
8448 report.installerPackageName = r.errorReportReceiver.getPackageName();
8449 report.processName = r.processName;
8450 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008451 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008452
Dan Egnorb7f03672009-12-09 16:22:32 -08008453 if (r.crashing) {
8454 report.type = ApplicationErrorReport.TYPE_CRASH;
8455 report.crashInfo = crashInfo;
8456 } else if (r.notResponding) {
8457 report.type = ApplicationErrorReport.TYPE_ANR;
8458 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008459
Dan Egnorb7f03672009-12-09 16:22:32 -08008460 report.anrInfo.activity = r.notRespondingReport.tag;
8461 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8462 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008463 }
8464
Dan Egnorb7f03672009-12-09 16:22:32 -08008465 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008466 }
8467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008468 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008469 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008470 // assume our apps are happy - lazy create the list
8471 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8472
Dianne Hackborn0c380492012-08-20 17:23:30 -07008473 final boolean allUsers = ActivityManager.checkUidPermission(
8474 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8475 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8476 int userId = UserHandle.getUserId(Binder.getCallingUid());
8477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008478 synchronized (this) {
8479
8480 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008481 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8482 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008483 if (!allUsers && app.userId != userId) {
8484 continue;
8485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008486 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8487 // This one's in trouble, so we'll generate a report for it
8488 // crashes are higher priority (in case there's a crash *and* an anr)
8489 ActivityManager.ProcessErrorStateInfo report = null;
8490 if (app.crashing) {
8491 report = app.crashingReport;
8492 } else if (app.notResponding) {
8493 report = app.notRespondingReport;
8494 }
8495
8496 if (report != null) {
8497 if (errList == null) {
8498 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8499 }
8500 errList.add(report);
8501 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008502 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 " crashing = " + app.crashing +
8504 " notResponding = " + app.notResponding);
8505 }
8506 }
8507 }
8508 }
8509
8510 return errList;
8511 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008512
8513 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008514 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008515 if (currApp != null) {
8516 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8517 }
8518 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008519 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8520 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008521 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8522 if (currApp != null) {
8523 currApp.lru = 0;
8524 }
8525 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008526 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008527 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8528 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8529 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8530 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8531 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8532 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8533 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8534 } else {
8535 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8536 }
8537 }
8538
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008539 private void fillInProcMemInfo(ProcessRecord app,
8540 ActivityManager.RunningAppProcessInfo outInfo) {
8541 outInfo.pid = app.pid;
8542 outInfo.uid = app.info.uid;
8543 if (mHeavyWeightProcess == app) {
8544 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8545 }
8546 if (app.persistent) {
8547 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8548 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008549 if (app.hasActivities) {
8550 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8551 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008552 outInfo.lastTrimLevel = app.trimMemoryLevel;
8553 int adj = app.curAdj;
8554 outInfo.importance = oomAdjToImportance(adj, outInfo);
8555 outInfo.importanceReasonCode = app.adjTypeCode;
8556 }
8557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008558 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008559 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008560 // Lazy instantiation of list
8561 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008562 final boolean allUsers = ActivityManager.checkUidPermission(
8563 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8564 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8565 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008566 synchronized (this) {
8567 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008568 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8569 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008570 if (!allUsers && app.userId != userId) {
8571 continue;
8572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008573 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8574 // Generate process state info for running application
8575 ActivityManager.RunningAppProcessInfo currApp =
8576 new ActivityManager.RunningAppProcessInfo(app.processName,
8577 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008578 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008579 if (app.adjSource instanceof ProcessRecord) {
8580 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008581 currApp.importanceReasonImportance = oomAdjToImportance(
8582 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008583 } else if (app.adjSource instanceof ActivityRecord) {
8584 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008585 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8586 }
8587 if (app.adjTarget instanceof ComponentName) {
8588 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8589 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008590 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591 // + " lru=" + currApp.lru);
8592 if (runList == null) {
8593 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8594 }
8595 runList.add(currApp);
8596 }
8597 }
8598 }
8599 return runList;
8600 }
8601
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008602 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008603 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008604 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8605 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8606 if (runningApps != null && runningApps.size() > 0) {
8607 Set<String> extList = new HashSet<String>();
8608 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8609 if (app.pkgList != null) {
8610 for (String pkg : app.pkgList) {
8611 extList.add(pkg);
8612 }
8613 }
8614 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008615 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008616 for (String pkg : extList) {
8617 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008618 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008619 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8620 retList.add(info);
8621 }
8622 } catch (RemoteException e) {
8623 }
8624 }
8625 }
8626 return retList;
8627 }
8628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008630 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8631 enforceNotIsolatedCaller("getMyMemoryState");
8632 synchronized (this) {
8633 ProcessRecord proc;
8634 synchronized (mPidsSelfLocked) {
8635 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8636 }
8637 fillInProcMemInfo(proc, outInfo);
8638 }
8639 }
8640
8641 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008642 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008643 if (checkCallingPermission(android.Manifest.permission.DUMP)
8644 != PackageManager.PERMISSION_GRANTED) {
8645 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8646 + Binder.getCallingPid()
8647 + ", uid=" + Binder.getCallingUid()
8648 + " without permission "
8649 + android.Manifest.permission.DUMP);
8650 return;
8651 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008652
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008653 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008654 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008655 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008656
8657 int opti = 0;
8658 while (opti < args.length) {
8659 String opt = args[opti];
8660 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8661 break;
8662 }
8663 opti++;
8664 if ("-a".equals(opt)) {
8665 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008666 } else if ("-c".equals(opt)) {
8667 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008668 } else if ("-h".equals(opt)) {
8669 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008670 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008671 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008672 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008673 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8674 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8675 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008676 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008677 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008678 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008679 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008680 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008681 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008682 pw.println(" all: dump all activities");
8683 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008684 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008685 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8686 pw.println(" a partial substring in a component name, a");
8687 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008688 pw.println(" -a: include all available server state.");
8689 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008691 } else {
8692 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008693 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008694 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008695
8696 long origId = Binder.clearCallingIdentity();
8697 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008698 // Is the caller requesting to dump a particular piece of data?
8699 if (opti < args.length) {
8700 String cmd = args[opti];
8701 opti++;
8702 if ("activities".equals(cmd) || "a".equals(cmd)) {
8703 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008704 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008705 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008706 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008707 String[] newArgs;
8708 String name;
8709 if (opti >= args.length) {
8710 name = null;
8711 newArgs = EMPTY_STRING_ARRAY;
8712 } else {
8713 name = args[opti];
8714 opti++;
8715 newArgs = new String[args.length - opti];
8716 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8717 args.length - opti);
8718 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008719 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008720 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008721 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008722 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008723 String[] newArgs;
8724 String name;
8725 if (opti >= args.length) {
8726 name = null;
8727 newArgs = EMPTY_STRING_ARRAY;
8728 } else {
8729 name = args[opti];
8730 opti++;
8731 newArgs = new String[args.length - opti];
8732 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8733 args.length - opti);
8734 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008735 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008736 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008737 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008738 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008739 String[] newArgs;
8740 String name;
8741 if (opti >= args.length) {
8742 name = null;
8743 newArgs = EMPTY_STRING_ARRAY;
8744 } else {
8745 name = args[opti];
8746 opti++;
8747 newArgs = new String[args.length - opti];
8748 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8749 args.length - opti);
8750 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008751 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008752 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008753 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008754 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8755 synchronized (this) {
8756 dumpOomLocked(fd, pw, args, opti, true);
8757 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008758 } else if ("provider".equals(cmd)) {
8759 String[] newArgs;
8760 String name;
8761 if (opti >= args.length) {
8762 name = null;
8763 newArgs = EMPTY_STRING_ARRAY;
8764 } else {
8765 name = args[opti];
8766 opti++;
8767 newArgs = new String[args.length - opti];
8768 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8769 }
8770 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8771 pw.println("No providers match: " + name);
8772 pw.println("Use -h for help.");
8773 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008774 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8775 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008776 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008777 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008778 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008779 String[] newArgs;
8780 String name;
8781 if (opti >= args.length) {
8782 name = null;
8783 newArgs = EMPTY_STRING_ARRAY;
8784 } else {
8785 name = args[opti];
8786 opti++;
8787 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008788 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8789 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008790 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008791 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008792 pw.println("No services match: " + name);
8793 pw.println("Use -h for help.");
8794 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008795 } else if ("package".equals(cmd)) {
8796 String[] newArgs;
8797 if (opti >= args.length) {
8798 pw.println("package: no package name specified");
8799 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008800 } else {
8801 dumpPackage = args[opti];
8802 opti++;
8803 newArgs = new String[args.length - opti];
8804 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8805 args.length - opti);
8806 args = newArgs;
8807 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008808 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008809 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008810 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8811 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008812 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008813 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008814 } else {
8815 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008816 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8817 pw.println("Bad activity command, or no activities match: " + cmd);
8818 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008819 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008820 }
8821 if (!more) {
8822 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008823 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008824 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008825 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008826
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008827 // No piece of data specified, dump everything.
8828 synchronized (this) {
8829 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008830 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008831 if (needSep) {
8832 pw.println(" ");
8833 }
8834 if (dumpAll) {
8835 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008836 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008837 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008838 if (needSep) {
8839 pw.println(" ");
8840 }
8841 if (dumpAll) {
8842 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008843 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008844 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008845 if (needSep) {
8846 pw.println(" ");
8847 }
8848 if (dumpAll) {
8849 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008850 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008851 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008852 if (needSep) {
8853 pw.println(" ");
8854 }
8855 if (dumpAll) {
8856 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008857 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008858 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008859 if (needSep) {
8860 pw.println(" ");
8861 }
8862 if (dumpAll) {
8863 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008864 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008865 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008866 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008867 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008868 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008869
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008870 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008871 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008872 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8873 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008874 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8875 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008876 pw.println(" ");
8877 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008878 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8879 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008880 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008881 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008882 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008883 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008884 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008885 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008886 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008887 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008888 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008889 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008890 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008891 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008892 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8893 pw.println(" ");
8894 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008895 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008896 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008897 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008898 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008899 pw.println(" ");
8900 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008901 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008902 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008904
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008905 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008906 if (mMainStack.mPausingActivity != null) {
8907 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008908 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008909 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008910 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008911 if (dumpAll) {
8912 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8913 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008914 pw.println(" mDismissKeyguardOnNextActivity: "
8915 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008917
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008918 if (mRecentTasks.size() > 0) {
8919 pw.println();
8920 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008921
8922 final int N = mRecentTasks.size();
8923 for (int i=0; i<N; i++) {
8924 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008925 if (dumpPackage != null) {
8926 if (tr.realActivity == null ||
8927 !dumpPackage.equals(tr.realActivity)) {
8928 continue;
8929 }
8930 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008931 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8932 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008933 if (dumpAll) {
8934 mRecentTasks.get(i).dump(pw, " ");
8935 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008936 }
8937 }
8938
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008939 if (dumpAll) {
8940 pw.println(" ");
8941 pw.println(" mCurTask: " + mCurTask);
8942 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008943
8944 return true;
8945 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008946
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008947 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008948 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008949 boolean needSep = false;
8950 int numPers = 0;
8951
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008952 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8953
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008954 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8956 final int NA = procs.size();
8957 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008958 ProcessRecord r = procs.valueAt(ia);
8959 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8960 continue;
8961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008962 if (!needSep) {
8963 pw.println(" All known processes:");
8964 needSep = true;
8965 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008966 pw.print(r.persistent ? " *PERS*" : " *APP*");
8967 pw.print(" UID "); pw.print(procs.keyAt(ia));
8968 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008969 r.dump(pw, " ");
8970 if (r.persistent) {
8971 numPers++;
8972 }
8973 }
8974 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008975 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008976
8977 if (mIsolatedProcesses.size() > 0) {
8978 if (needSep) pw.println(" ");
8979 needSep = true;
8980 pw.println(" Isolated process list (sorted by uid):");
8981 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8982 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8983 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8984 continue;
8985 }
8986 pw.println(String.format("%sIsolated #%2d: %s",
8987 " ", i, r.toString()));
8988 }
8989 }
8990
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008991 if (mLruProcesses.size() > 0) {
8992 if (needSep) pw.println(" ");
8993 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008994 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008995 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008996 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008997 needSep = true;
8998 }
8999
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009000 if (dumpAll) {
9001 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009002 boolean printed = false;
9003 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9004 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9005 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9006 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009007 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009008 if (!printed) {
9009 if (needSep) pw.println(" ");
9010 needSep = true;
9011 pw.println(" PID mappings:");
9012 printed = true;
9013 }
9014 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9015 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009016 }
9017 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009018 }
9019
9020 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009021 synchronized (mPidsSelfLocked) {
9022 boolean printed = false;
9023 for (int i=0; i<mForegroundProcesses.size(); i++) {
9024 ProcessRecord r = mPidsSelfLocked.get(
9025 mForegroundProcesses.valueAt(i).pid);
9026 if (dumpPackage != null && (r == null
9027 || !dumpPackage.equals(r.info.packageName))) {
9028 continue;
9029 }
9030 if (!printed) {
9031 if (needSep) pw.println(" ");
9032 needSep = true;
9033 pw.println(" Foreground Processes:");
9034 printed = true;
9035 }
9036 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9037 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009039 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009040 }
9041
9042 if (mPersistentStartingProcesses.size() > 0) {
9043 if (needSep) pw.println(" ");
9044 needSep = true;
9045 pw.println(" Persisent processes that are starting:");
9046 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009047 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009049
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009050 if (mRemovedProcesses.size() > 0) {
9051 if (needSep) pw.println(" ");
9052 needSep = true;
9053 pw.println(" Processes that are being removed:");
9054 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009055 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009056 }
9057
9058 if (mProcessesOnHold.size() > 0) {
9059 if (needSep) pw.println(" ");
9060 needSep = true;
9061 pw.println(" Processes that are on old until the system is ready:");
9062 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009063 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009066 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009067
9068 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009069 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009070 long now = SystemClock.uptimeMillis();
9071 for (Map.Entry<String, SparseArray<Long>> procs
9072 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009073 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009074 SparseArray<Long> uids = procs.getValue();
9075 final int N = uids.size();
9076 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009077 int puid = uids.keyAt(i);
9078 ProcessRecord r = mProcessNames.get(pname, puid);
9079 if (dumpPackage != null && (r == null
9080 || !dumpPackage.equals(r.info.packageName))) {
9081 continue;
9082 }
9083 if (!printed) {
9084 if (needSep) pw.println(" ");
9085 needSep = true;
9086 pw.println(" Time since processes crashed:");
9087 printed = true;
9088 }
9089 pw.print(" Process "); pw.print(pname);
9090 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009091 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009092 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9093 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009094 }
9095 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009097
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009098 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009099 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009100 for (Map.Entry<String, SparseArray<Long>> procs
9101 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009102 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009103 SparseArray<Long> uids = procs.getValue();
9104 final int N = uids.size();
9105 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009106 int puid = uids.keyAt(i);
9107 ProcessRecord r = mProcessNames.get(pname, puid);
9108 if (dumpPackage != null && (r == null
9109 || !dumpPackage.equals(r.info.packageName))) {
9110 continue;
9111 }
9112 if (!printed) {
9113 if (needSep) pw.println(" ");
9114 needSep = true;
9115 pw.println(" Bad processes:");
9116 }
9117 pw.print(" Bad process "); pw.print(pname);
9118 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009119 pw.print(": crashed at time ");
9120 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009121 }
9122 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009124
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009125 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009126 pw.println(" mStartedUsers:");
9127 for (int i=0; i<mStartedUsers.size(); i++) {
9128 UserStartedState uss = mStartedUsers.valueAt(i);
9129 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
9130 pw.println(":");
9131 uss.dump(" ", pw);
9132 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009133 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009134 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009135 if (dumpAll) {
9136 StringBuilder sb = new StringBuilder(128);
9137 sb.append(" mPreviousProcessVisibleTime: ");
9138 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9139 pw.println(sb);
9140 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009141 if (mHeavyWeightProcess != null) {
9142 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9143 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009144 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009145 if (dumpAll) {
9146 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009147 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009148 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009149 for (Map.Entry<String, Integer> entry
9150 : mCompatModePackages.getPackages().entrySet()) {
9151 String pkg = entry.getKey();
9152 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009153 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9154 continue;
9155 }
9156 if (!printed) {
9157 pw.println(" mScreenCompatPackages:");
9158 printed = true;
9159 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009160 pw.print(" "); pw.print(pkg); pw.print(": ");
9161 pw.print(mode); pw.println();
9162 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009163 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009164 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009165 if (mSleeping || mWentToSleep || mLockScreenShown) {
9166 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9167 + " mLockScreenShown " + mLockScreenShown);
9168 }
9169 if (mShuttingDown) {
9170 pw.println(" mShuttingDown=" + mShuttingDown);
9171 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009172 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9173 || mOrigWaitForDebugger) {
9174 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9175 + " mDebugTransient=" + mDebugTransient
9176 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9177 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009178 if (mOpenGlTraceApp != null) {
9179 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9180 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009181 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9182 || mProfileFd != null) {
9183 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9184 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9185 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9186 + mAutoStopProfiler);
9187 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009188 if (mAlwaysFinishActivities || mController != null) {
9189 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9190 + " mController=" + mController);
9191 }
9192 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009193 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009194 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009195 + " mProcessesReady=" + mProcessesReady
9196 + " mSystemReady=" + mSystemReady);
9197 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009198 + " mBooted=" + mBooted
9199 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009200 pw.print(" mLastPowerCheckRealtime=");
9201 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9202 pw.println("");
9203 pw.print(" mLastPowerCheckUptime=");
9204 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9205 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009206 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9207 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009208 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009209 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9210 + " mNumHiddenProcs=" + mNumHiddenProcs
9211 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009212 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009213 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009214
9215 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009216 }
9217
Dianne Hackborn287952c2010-09-22 22:34:31 -07009218 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009219 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009220 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009221 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009222 long now = SystemClock.uptimeMillis();
9223 for (int i=0; i<mProcessesToGc.size(); i++) {
9224 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009225 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9226 continue;
9227 }
9228 if (!printed) {
9229 if (needSep) pw.println(" ");
9230 needSep = true;
9231 pw.println(" Processes that are waiting to GC:");
9232 printed = true;
9233 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009234 pw.print(" Process "); pw.println(proc);
9235 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9236 pw.print(", last gced=");
9237 pw.print(now-proc.lastRequestedGc);
9238 pw.print(" ms ago, last lowMem=");
9239 pw.print(now-proc.lastLowMemory);
9240 pw.println(" ms ago");
9241
9242 }
9243 }
9244 return needSep;
9245 }
9246
9247 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9248 int opti, boolean dumpAll) {
9249 boolean needSep = false;
9250
9251 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009252 if (needSep) pw.println(" ");
9253 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009254 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009255 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009256 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009257 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9258 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9259 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9260 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9261 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009262 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009263 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009264 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009265 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009266 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009267 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009268
9269 if (needSep) pw.println(" ");
9270 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009271 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009272 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009273 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009274 needSep = true;
9275 }
9276
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009277 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009278
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009279 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009280 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009281 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009282 if (mHeavyWeightProcess != null) {
9283 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9284 }
9285
9286 return true;
9287 }
9288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009289 /**
9290 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009291 * - no provider specified: dump all the providers
9292 * - a flattened component name that matched an existing provider was specified as the
9293 * first arg: dump that one provider
9294 * - the first arg isn't the flattened component name of an existing provider:
9295 * dump all providers whose component contains the first arg as a substring
9296 */
9297 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9298 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009299 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009300 }
9301
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009302 static class ItemMatcher {
9303 ArrayList<ComponentName> components;
9304 ArrayList<String> strings;
9305 ArrayList<Integer> objects;
9306 boolean all;
9307
9308 ItemMatcher() {
9309 all = true;
9310 }
9311
9312 void build(String name) {
9313 ComponentName componentName = ComponentName.unflattenFromString(name);
9314 if (componentName != null) {
9315 if (components == null) {
9316 components = new ArrayList<ComponentName>();
9317 }
9318 components.add(componentName);
9319 all = false;
9320 } else {
9321 int objectId = 0;
9322 // Not a '/' separated full component name; maybe an object ID?
9323 try {
9324 objectId = Integer.parseInt(name, 16);
9325 if (objects == null) {
9326 objects = new ArrayList<Integer>();
9327 }
9328 objects.add(objectId);
9329 all = false;
9330 } catch (RuntimeException e) {
9331 // Not an integer; just do string match.
9332 if (strings == null) {
9333 strings = new ArrayList<String>();
9334 }
9335 strings.add(name);
9336 all = false;
9337 }
9338 }
9339 }
9340
9341 int build(String[] args, int opti) {
9342 for (; opti<args.length; opti++) {
9343 String name = args[opti];
9344 if ("--".equals(name)) {
9345 return opti+1;
9346 }
9347 build(name);
9348 }
9349 return opti;
9350 }
9351
9352 boolean match(Object object, ComponentName comp) {
9353 if (all) {
9354 return true;
9355 }
9356 if (components != null) {
9357 for (int i=0; i<components.size(); i++) {
9358 if (components.get(i).equals(comp)) {
9359 return true;
9360 }
9361 }
9362 }
9363 if (objects != null) {
9364 for (int i=0; i<objects.size(); i++) {
9365 if (System.identityHashCode(object) == objects.get(i)) {
9366 return true;
9367 }
9368 }
9369 }
9370 if (strings != null) {
9371 String flat = comp.flattenToString();
9372 for (int i=0; i<strings.size(); i++) {
9373 if (flat.contains(strings.get(i))) {
9374 return true;
9375 }
9376 }
9377 }
9378 return false;
9379 }
9380 }
9381
Dianne Hackborn625ac272010-09-17 18:29:22 -07009382 /**
9383 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009384 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009385 * - the cmd arg isn't the flattened component name of an existing activity:
9386 * dump all activity whose component contains the cmd as a substring
9387 * - A hex number of the ActivityRecord object instance.
9388 */
9389 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9390 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009391 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009392
9393 if ("all".equals(name)) {
9394 synchronized (this) {
9395 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009396 activities.add(r1);
9397 }
9398 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009399 } else if ("top".equals(name)) {
9400 synchronized (this) {
9401 final int N = mMainStack.mHistory.size();
9402 if (N > 0) {
9403 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9404 }
9405 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009406 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009407 ItemMatcher matcher = new ItemMatcher();
9408 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009409
9410 synchronized (this) {
9411 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009412 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009413 activities.add(r1);
9414 }
9415 }
9416 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009417 }
9418
9419 if (activities.size() <= 0) {
9420 return false;
9421 }
9422
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009423 String[] newArgs = new String[args.length - opti];
9424 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9425
Dianne Hackborn30d71892010-12-11 10:37:55 -08009426 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009427 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009428 for (int i=activities.size()-1; i>=0; i--) {
9429 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009430 if (needSep) {
9431 pw.println();
9432 }
9433 needSep = true;
9434 synchronized (this) {
9435 if (lastTask != r.task) {
9436 lastTask = r.task;
9437 pw.print("TASK "); pw.print(lastTask.affinity);
9438 pw.print(" id="); pw.println(lastTask.taskId);
9439 if (dumpAll) {
9440 lastTask.dump(pw, " ");
9441 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009442 }
9443 }
9444 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009445 }
9446 return true;
9447 }
9448
9449 /**
9450 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9451 * there is a thread associated with the activity.
9452 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009453 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009454 final ActivityRecord r, String[] args, boolean dumpAll) {
9455 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009456 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009457 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9458 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9459 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009460 if (r.app != null) pw.println(r.app.pid);
9461 else pw.println("(not running)");
9462 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009463 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009464 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009465 }
9466 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009467 // flush anything that is already in the PrintWriter since the thread is going
9468 // to write to the file descriptor directly
9469 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009470 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009471 TransferPipe tp = new TransferPipe();
9472 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009473 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9474 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009475 tp.go(fd);
9476 } finally {
9477 tp.kill();
9478 }
9479 } catch (IOException e) {
9480 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009481 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009482 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009483 }
9484 }
9485 }
9486
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009487 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009488 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009489 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009490 boolean onlyHistory = false;
9491
9492 if ("history".equals(dumpPackage)) {
9493 onlyHistory = true;
9494 dumpPackage = null;
9495 }
9496
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009497 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009498 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009499 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009500 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009501 Iterator it = mRegisteredReceivers.values().iterator();
9502 while (it.hasNext()) {
9503 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009504 if (dumpPackage != null && (r.app == null ||
9505 !dumpPackage.equals(r.app.info.packageName))) {
9506 continue;
9507 }
9508 if (!printed) {
9509 pw.println(" Registered Receivers:");
9510 needSep = true;
9511 printed = true;
9512 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009513 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009514 r.dump(pw, " ");
9515 }
9516 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009517
9518 if (mReceiverResolver.dump(pw, needSep ?
9519 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9520 " ", dumpPackage, false)) {
9521 needSep = true;
9522 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009523 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009524
9525 for (BroadcastQueue q : mBroadcastQueues) {
9526 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009528
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009529 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009530
Dianne Hackborn786b4402012-08-27 15:14:02 -07009531 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009532 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9533 if (needSep) {
9534 pw.println();
9535 }
9536 needSep = true;
9537 pw.print(" Sticky broadcasts for user ");
9538 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9539 StringBuilder sb = new StringBuilder(128);
9540 for (Map.Entry<String, ArrayList<Intent>> ent
9541 : mStickyBroadcasts.valueAt(user).entrySet()) {
9542 pw.print(" * Sticky action "); pw.print(ent.getKey());
9543 if (dumpAll) {
9544 pw.println(":");
9545 ArrayList<Intent> intents = ent.getValue();
9546 final int N = intents.size();
9547 for (int i=0; i<N; i++) {
9548 sb.setLength(0);
9549 sb.append(" Intent: ");
9550 intents.get(i).toShortString(sb, false, true, false, false);
9551 pw.println(sb.toString());
9552 Bundle bundle = intents.get(i).getExtras();
9553 if (bundle != null) {
9554 pw.print(" ");
9555 pw.println(bundle.toString());
9556 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009557 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009558 } else {
9559 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009560 }
9561 }
9562 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009563 }
9564
Dianne Hackborn786b4402012-08-27 15:14:02 -07009565 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009566 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009567 for (BroadcastQueue queue : mBroadcastQueues) {
9568 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9569 + queue.mBroadcastsScheduled);
9570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009571 pw.println(" mHandler:");
9572 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009573 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009574 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009575
9576 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009577 }
9578
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009579 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009580 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009581 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009582
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009583 ItemMatcher matcher = new ItemMatcher();
9584 matcher.build(args, opti);
9585
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009586 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009587
9588 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009589
9590 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009591 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009592 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009593 ContentProviderRecord r = mLaunchingProviders.get(i);
9594 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9595 continue;
9596 }
9597 if (!printed) {
9598 if (needSep) pw.println(" ");
9599 needSep = true;
9600 pw.println(" Launching content providers:");
9601 printed = true;
9602 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009603 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009604 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009605 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009606 }
9607
9608 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009609 if (needSep) pw.println();
9610 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009611 pw.println("Granted Uri Permissions:");
9612 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9613 int uid = mGrantedUriPermissions.keyAt(i);
9614 HashMap<Uri, UriPermission> perms
9615 = mGrantedUriPermissions.valueAt(i);
9616 pw.print(" * UID "); pw.print(uid);
9617 pw.println(" holds:");
9618 for (UriPermission perm : perms.values()) {
9619 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009620 if (dumpAll) {
9621 perm.dump(pw, " ");
9622 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009623 }
9624 }
9625 needSep = true;
9626 }
9627
9628 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009629 }
9630
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009631 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009632 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009633 boolean needSep = false;
9634
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009635 if (mIntentSenderRecords.size() > 0) {
9636 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009637 Iterator<WeakReference<PendingIntentRecord>> it
9638 = mIntentSenderRecords.values().iterator();
9639 while (it.hasNext()) {
9640 WeakReference<PendingIntentRecord> ref = it.next();
9641 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009642 if (dumpPackage != null && (rec == null
9643 || !dumpPackage.equals(rec.key.packageName))) {
9644 continue;
9645 }
9646 if (!printed) {
9647 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9648 printed = true;
9649 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009650 needSep = true;
9651 if (rec != null) {
9652 pw.print(" * "); pw.println(rec);
9653 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009654 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009655 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009656 } else {
9657 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009658 }
9659 }
9660 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009661
9662 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009663 }
9664
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009665 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009666 String prefix, String label, boolean complete, boolean brief, boolean client,
9667 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009668 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009669 boolean needNL = false;
9670 final String innerPrefix = prefix + " ";
9671 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009672 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009673 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009674 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9675 continue;
9676 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009677 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009678 if (needNL) {
9679 pw.println(" ");
9680 needNL = false;
9681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009682 if (lastTask != r.task) {
9683 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009684 pw.print(prefix);
9685 pw.print(full ? "* " : " ");
9686 pw.println(lastTask);
9687 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009688 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009689 } else if (complete) {
9690 // Complete + brief == give a summary. Isn't that obvious?!?
9691 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009692 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009693 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009694 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009696 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009697 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9698 pw.print(" #"); pw.print(i); pw.print(": ");
9699 pw.println(r);
9700 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009701 r.dump(pw, innerPrefix);
9702 } else if (complete) {
9703 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009704 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009705 if (r.app != null) {
9706 pw.print(innerPrefix); pw.println(r.app);
9707 }
9708 }
9709 if (client && r.app != null && r.app.thread != null) {
9710 // flush anything that is already in the PrintWriter since the thread is going
9711 // to write to the file descriptor directly
9712 pw.flush();
9713 try {
9714 TransferPipe tp = new TransferPipe();
9715 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009716 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9717 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009718 // Short timeout, since blocking here can
9719 // deadlock with the application.
9720 tp.go(fd, 2000);
9721 } finally {
9722 tp.kill();
9723 }
9724 } catch (IOException e) {
9725 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9726 } catch (RemoteException e) {
9727 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9728 }
9729 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009731 }
9732 }
9733
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009734 private static String buildOomTag(String prefix, String space, int val, int base) {
9735 if (val == base) {
9736 if (space == null) return prefix;
9737 return prefix + " ";
9738 }
9739 return prefix + "+" + Integer.toString(val-base);
9740 }
9741
9742 private static final int dumpProcessList(PrintWriter pw,
9743 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009744 String prefix, String normalLabel, String persistentLabel,
9745 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009746 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009747 final int N = list.size()-1;
9748 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009749 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009750 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9751 continue;
9752 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009753 pw.println(String.format("%s%s #%2d: %s",
9754 prefix, (r.persistent ? persistentLabel : normalLabel),
9755 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009756 if (r.persistent) {
9757 numPers++;
9758 }
9759 }
9760 return numPers;
9761 }
9762
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009763 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009764 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009765 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009766 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009767
Dianne Hackborn905577f2011-09-07 18:31:28 -07009768 ArrayList<Pair<ProcessRecord, Integer>> list
9769 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9770 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009771 ProcessRecord r = origList.get(i);
9772 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9773 continue;
9774 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009775 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9776 }
9777
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009778 if (list.size() <= 0) {
9779 return false;
9780 }
9781
Dianne Hackborn905577f2011-09-07 18:31:28 -07009782 Comparator<Pair<ProcessRecord, Integer>> comparator
9783 = new Comparator<Pair<ProcessRecord, Integer>>() {
9784 @Override
9785 public int compare(Pair<ProcessRecord, Integer> object1,
9786 Pair<ProcessRecord, Integer> object2) {
9787 if (object1.first.setAdj != object2.first.setAdj) {
9788 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9789 }
9790 if (object1.second.intValue() != object2.second.intValue()) {
9791 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9792 }
9793 return 0;
9794 }
9795 };
9796
9797 Collections.sort(list, comparator);
9798
Dianne Hackborn287952c2010-09-22 22:34:31 -07009799 final long curRealtime = SystemClock.elapsedRealtime();
9800 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9801 final long curUptime = SystemClock.uptimeMillis();
9802 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9803
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009804 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009805 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009806 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009807 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009808 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009809 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9810 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009811 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9812 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009813 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9814 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009815 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9816 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009817 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009818 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009819 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9820 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9821 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9822 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9823 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9824 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9825 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9826 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009827 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9828 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009829 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9830 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009831 } else {
9832 oomAdj = Integer.toString(r.setAdj);
9833 }
9834 String schedGroup;
9835 switch (r.setSchedGroup) {
9836 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9837 schedGroup = "B";
9838 break;
9839 case Process.THREAD_GROUP_DEFAULT:
9840 schedGroup = "F";
9841 break;
9842 default:
9843 schedGroup = Integer.toString(r.setSchedGroup);
9844 break;
9845 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009846 String foreground;
9847 if (r.foregroundActivities) {
9848 foreground = "A";
9849 } else if (r.foregroundServices) {
9850 foreground = "S";
9851 } else {
9852 foreground = " ";
9853 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009854 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009855 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009856 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9857 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009858 if (r.adjSource != null || r.adjTarget != null) {
9859 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009860 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009861 if (r.adjTarget instanceof ComponentName) {
9862 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9863 } else if (r.adjTarget != null) {
9864 pw.print(r.adjTarget.toString());
9865 } else {
9866 pw.print("{null}");
9867 }
9868 pw.print("<=");
9869 if (r.adjSource instanceof ProcessRecord) {
9870 pw.print("Proc{");
9871 pw.print(((ProcessRecord)r.adjSource).toShortString());
9872 pw.println("}");
9873 } else if (r.adjSource != null) {
9874 pw.println(r.adjSource.toString());
9875 } else {
9876 pw.println("{null}");
9877 }
9878 }
9879 if (inclDetails) {
9880 pw.print(prefix);
9881 pw.print(" ");
9882 pw.print("oom: max="); pw.print(r.maxAdj);
9883 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009884 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009885 pw.print(" curRaw="); pw.print(r.curRawAdj);
9886 pw.print(" setRaw="); pw.print(r.setRawAdj);
9887 pw.print(" cur="); pw.print(r.curAdj);
9888 pw.print(" set="); pw.println(r.setAdj);
9889 pw.print(prefix);
9890 pw.print(" ");
9891 pw.print("keeping="); pw.print(r.keeping);
9892 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009893 pw.print(" empty="); pw.print(r.empty);
9894 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009895
9896 if (!r.keeping) {
9897 if (r.lastWakeTime != 0) {
9898 long wtime;
9899 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9900 synchronized (stats) {
9901 wtime = stats.getProcessWakeTime(r.info.uid,
9902 r.pid, curRealtime);
9903 }
9904 long timeUsed = wtime - r.lastWakeTime;
9905 pw.print(prefix);
9906 pw.print(" ");
9907 pw.print("keep awake over ");
9908 TimeUtils.formatDuration(realtimeSince, pw);
9909 pw.print(" used ");
9910 TimeUtils.formatDuration(timeUsed, pw);
9911 pw.print(" (");
9912 pw.print((timeUsed*100)/realtimeSince);
9913 pw.println("%)");
9914 }
9915 if (r.lastCpuTime != 0) {
9916 long timeUsed = r.curCpuTime - r.lastCpuTime;
9917 pw.print(prefix);
9918 pw.print(" ");
9919 pw.print("run cpu over ");
9920 TimeUtils.formatDuration(uptimeSince, pw);
9921 pw.print(" used ");
9922 TimeUtils.formatDuration(timeUsed, pw);
9923 pw.print(" (");
9924 pw.print((timeUsed*100)/uptimeSince);
9925 pw.println("%)");
9926 }
9927 }
9928 }
9929 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009930 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009931 }
9932
Dianne Hackbornb437e092011-08-05 17:50:29 -07009933 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009934 ArrayList<ProcessRecord> procs;
9935 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009936 if (args != null && args.length > start
9937 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009938 procs = new ArrayList<ProcessRecord>();
9939 int pid = -1;
9940 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009941 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009942 } catch (NumberFormatException e) {
9943
9944 }
9945 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9946 ProcessRecord proc = mLruProcesses.get(i);
9947 if (proc.pid == pid) {
9948 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009949 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009950 procs.add(proc);
9951 }
9952 }
9953 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009954 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009955 return null;
9956 }
9957 } else {
9958 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9959 }
9960 }
9961 return procs;
9962 }
9963
9964 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9965 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009966 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009967 if (procs == null) {
9968 return;
9969 }
9970
9971 long uptime = SystemClock.uptimeMillis();
9972 long realtime = SystemClock.elapsedRealtime();
9973 pw.println("Applications Graphics Acceleration Info:");
9974 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9975
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009976 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9977 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009978 if (r.thread != null) {
9979 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9980 pw.flush();
9981 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009982 TransferPipe tp = new TransferPipe();
9983 try {
9984 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9985 tp.go(fd);
9986 } finally {
9987 tp.kill();
9988 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009989 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009990 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009991 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009992 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009993 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009994 pw.flush();
9995 }
9996 }
9997 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009998 }
9999
Jeff Brown6754ba22011-12-14 20:20:01 -080010000 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10001 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10002 if (procs == null) {
10003 return;
10004 }
10005
10006 pw.println("Applications Database Info:");
10007
10008 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10009 ProcessRecord r = procs.get(i);
10010 if (r.thread != null) {
10011 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10012 pw.flush();
10013 try {
10014 TransferPipe tp = new TransferPipe();
10015 try {
10016 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10017 tp.go(fd);
10018 } finally {
10019 tp.kill();
10020 }
10021 } catch (IOException e) {
10022 pw.println("Failure while dumping the app: " + r);
10023 pw.flush();
10024 } catch (RemoteException e) {
10025 pw.println("Got a RemoteException while dumping the app " + r);
10026 pw.flush();
10027 }
10028 }
10029 }
10030 }
10031
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010032 final static class MemItem {
10033 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010034 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010035 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010036 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010037 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010038
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010039 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010040 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010041 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010042 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010043 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010044 }
10045 }
10046
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010047 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010048 boolean sort) {
10049 if (sort) {
10050 Collections.sort(items, new Comparator<MemItem>() {
10051 @Override
10052 public int compare(MemItem lhs, MemItem rhs) {
10053 if (lhs.pss < rhs.pss) {
10054 return 1;
10055 } else if (lhs.pss > rhs.pss) {
10056 return -1;
10057 }
10058 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010059 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010060 });
10061 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010062
10063 for (int i=0; i<items.size(); i++) {
10064 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010065 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010066 if (mi.subitems != null) {
10067 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10068 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010069 }
10070 }
10071
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010072 // These are in KB.
10073 static final long[] DUMP_MEM_BUCKETS = new long[] {
10074 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10075 120*1024, 160*1024, 200*1024,
10076 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10077 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10078 };
10079
Dianne Hackborn672342c2011-11-29 11:29:02 -080010080 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10081 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010082 int start = label.lastIndexOf('.');
10083 if (start >= 0) start++;
10084 else start = 0;
10085 int end = label.length();
10086 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10087 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10088 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10089 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010090 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010091 out.append(label, start, end);
10092 return;
10093 }
10094 }
10095 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010096 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010097 out.append(label, start, end);
10098 }
10099
10100 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10101 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10102 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10103 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10104 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10105 };
10106 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10107 "System", "Persistent", "Foreground",
10108 "Visible", "Perceptible", "Heavy Weight",
10109 "Backup", "A Services", "Home", "Previous",
10110 "B Services", "Background"
10111 };
10112
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010113 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010114 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010115 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010116 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010117 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010118
10119 int opti = 0;
10120 while (opti < args.length) {
10121 String opt = args[opti];
10122 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10123 break;
10124 }
10125 opti++;
10126 if ("-a".equals(opt)) {
10127 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010128 } else if ("--oom".equals(opt)) {
10129 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010130 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010131 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010132 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010133 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010134 pw.println("If [process] is specified it can be the name or ");
10135 pw.println("pid of a specific process to dump.");
10136 return;
10137 } else {
10138 pw.println("Unknown argument: " + opt + "; use -h for help");
10139 }
10140 }
10141
10142 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010143 if (procs == null) {
10144 return;
10145 }
10146
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010147 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010148 long uptime = SystemClock.uptimeMillis();
10149 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010150
10151 if (procs.size() == 1 || isCheckinRequest) {
10152 dumpAll = true;
10153 }
10154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010155 if (isCheckinRequest) {
10156 // short checkin version
10157 pw.println(uptime + "," + realtime);
10158 pw.flush();
10159 } else {
10160 pw.println("Applications Memory Usage (kB):");
10161 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10162 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010163
Dianne Hackbornb437e092011-08-05 17:50:29 -070010164 String[] innerArgs = new String[args.length-opti];
10165 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10166
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010167 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10168 long nativePss=0, dalvikPss=0, otherPss=0;
10169 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10170
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010171 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10172 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10173 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010174
10175 long totalPss = 0;
10176
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010177 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10178 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010179 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010180 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010181 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10182 pw.flush();
10183 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010184 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010185 if (dumpAll) {
10186 try {
10187 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10188 } catch (RemoteException e) {
10189 if (!isCheckinRequest) {
10190 pw.println("Got RemoteException!");
10191 pw.flush();
10192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010193 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010194 } else {
10195 mi = new Debug.MemoryInfo();
10196 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010197 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010198
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010199 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010200 long myTotalPss = mi.getTotalPss();
10201 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010202 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010203 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010204 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010205
10206 nativePss += mi.nativePss;
10207 dalvikPss += mi.dalvikPss;
10208 otherPss += mi.otherPss;
10209 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10210 long mem = mi.getOtherPss(j);
10211 miscPss[j] += mem;
10212 otherPss -= mem;
10213 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010214
10215 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010216 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10217 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010218 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010219 if (oomProcs[oomIndex] == null) {
10220 oomProcs[oomIndex] = new ArrayList<MemItem>();
10221 }
10222 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010223 break;
10224 }
10225 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010227 }
10228 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010229
10230 if (!isCheckinRequest && procs.size() > 1) {
10231 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10232
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010233 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10234 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10235 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010236 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010237 String label = Debug.MemoryInfo.getOtherLabel(j);
10238 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010239 }
10240
Dianne Hackbornb437e092011-08-05 17:50:29 -070010241 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10242 for (int j=0; j<oomPss.length; j++) {
10243 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010244 String label = DUMP_MEM_OOM_LABEL[j];
10245 MemItem item = new MemItem(label, label, oomPss[j],
10246 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010247 item.subitems = oomProcs[j];
10248 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010249 }
10250 }
10251
Dianne Hackborn672342c2011-11-29 11:29:02 -080010252 if (outTag != null || outStack != null) {
10253 if (outTag != null) {
10254 appendMemBucket(outTag, totalPss, "total", false);
10255 }
10256 if (outStack != null) {
10257 appendMemBucket(outStack, totalPss, "total", true);
10258 }
10259 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010260 for (int i=0; i<oomMems.size(); i++) {
10261 MemItem miCat = oomMems.get(i);
10262 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10263 continue;
10264 }
10265 if (miCat.id < ProcessList.SERVICE_ADJ
10266 || miCat.id == ProcessList.HOME_APP_ADJ
10267 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010268 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10269 outTag.append(" / ");
10270 }
10271 if (outStack != null) {
10272 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10273 if (firstLine) {
10274 outStack.append(":");
10275 firstLine = false;
10276 }
10277 outStack.append("\n\t at ");
10278 } else {
10279 outStack.append("$");
10280 }
10281 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010282 for (int j=0; j<miCat.subitems.size(); j++) {
10283 MemItem mi = miCat.subitems.get(j);
10284 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010285 if (outTag != null) {
10286 outTag.append(" ");
10287 }
10288 if (outStack != null) {
10289 outStack.append("$");
10290 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010291 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010292 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10293 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10294 }
10295 if (outStack != null) {
10296 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10297 }
10298 }
10299 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10300 outStack.append("(");
10301 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10302 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10303 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10304 outStack.append(":");
10305 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10306 }
10307 }
10308 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010309 }
10310 }
10311 }
10312 }
10313
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010314 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010315 pw.println();
10316 pw.println("Total PSS by process:");
10317 dumpMemItems(pw, " ", procMems, true);
10318 pw.println();
10319 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010320 pw.println("Total PSS by OOM adjustment:");
10321 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010322 if (!oomOnly) {
10323 PrintWriter out = categoryPw != null ? categoryPw : pw;
10324 out.println();
10325 out.println("Total PSS by category:");
10326 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010327 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010328 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010329 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010330 final int[] SINGLE_LONG_FORMAT = new int[] {
10331 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10332 };
10333 long[] longOut = new long[1];
10334 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10335 SINGLE_LONG_FORMAT, null, longOut, null);
10336 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10337 longOut[0] = 0;
10338 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10339 SINGLE_LONG_FORMAT, null, longOut, null);
10340 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10341 longOut[0] = 0;
10342 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10343 SINGLE_LONG_FORMAT, null, longOut, null);
10344 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10345 longOut[0] = 0;
10346 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10347 SINGLE_LONG_FORMAT, null, longOut, null);
10348 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10349 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10350 pw.print(shared); pw.println(" kB");
10351 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10352 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010354 }
10355
10356 /**
10357 * Searches array of arguments for the specified string
10358 * @param args array of argument strings
10359 * @param value value to search for
10360 * @return true if the value is contained in the array
10361 */
10362 private static boolean scanArgs(String[] args, String value) {
10363 if (args != null) {
10364 for (String arg : args) {
10365 if (value.equals(arg)) {
10366 return true;
10367 }
10368 }
10369 }
10370 return false;
10371 }
10372
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010373 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10374 ContentProviderRecord cpr, boolean always) {
10375 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10376
10377 if (!inLaunching || always) {
10378 synchronized (cpr) {
10379 cpr.launchingApp = null;
10380 cpr.notifyAll();
10381 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010382 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010383 String names[] = cpr.info.authority.split(";");
10384 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010385 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010386 }
10387 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010388
10389 for (int i=0; i<cpr.connections.size(); i++) {
10390 ContentProviderConnection conn = cpr.connections.get(i);
10391 if (conn.waiting) {
10392 // If this connection is waiting for the provider, then we don't
10393 // need to mess with its process unless we are always removing
10394 // or for some reason the provider is not currently launching.
10395 if (inLaunching && !always) {
10396 continue;
10397 }
10398 }
10399 ProcessRecord capp = conn.client;
10400 conn.dead = true;
10401 if (conn.stableCount > 0) {
10402 if (!capp.persistent && capp.thread != null
10403 && capp.pid != 0
10404 && capp.pid != MY_PID) {
10405 Slog.i(TAG, "Kill " + capp.processName
10406 + " (pid " + capp.pid + "): provider " + cpr.info.name
10407 + " in dying process " + (proc != null ? proc.processName : "??"));
10408 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10409 capp.processName, capp.setAdj, "dying provider "
10410 + cpr.name.toShortString());
10411 Process.killProcessQuiet(capp.pid);
10412 }
10413 } else if (capp.thread != null && conn.provider.provider != null) {
10414 try {
10415 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10416 } catch (RemoteException e) {
10417 }
10418 // In the protocol here, we don't expect the client to correctly
10419 // clean up this connection, we'll just remove it.
10420 cpr.connections.remove(i);
10421 conn.client.conProviders.remove(conn);
10422 }
10423 }
10424
10425 if (inLaunching && always) {
10426 mLaunchingProviders.remove(cpr);
10427 }
10428 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010429 }
10430
10431 /**
10432 * Main code for cleaning up a process when it has gone away. This is
10433 * called both as a result of the process dying, or directly when stopping
10434 * a process when running in single process mode.
10435 */
10436 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010437 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010438 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010439 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010440 }
10441
Dianne Hackborn36124872009-10-08 16:22:03 -070010442 mProcessesToGc.remove(app);
10443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010444 // Dismiss any open dialogs.
10445 if (app.crashDialog != null) {
10446 app.crashDialog.dismiss();
10447 app.crashDialog = null;
10448 }
10449 if (app.anrDialog != null) {
10450 app.anrDialog.dismiss();
10451 app.anrDialog = null;
10452 }
10453 if (app.waitDialog != null) {
10454 app.waitDialog.dismiss();
10455 app.waitDialog = null;
10456 }
10457
10458 app.crashing = false;
10459 app.notResponding = false;
10460
10461 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010462 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010463 app.thread = null;
10464 app.forcingToForeground = null;
10465 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010466 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010467 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010468 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010469
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010470 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010471
10472 boolean restart = false;
10473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010474 // Remove published content providers.
10475 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010476 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010477 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010478 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010479
10480 final boolean always = app.bad || !allowRestart;
10481 if (removeDyingProviderLocked(app, cpr, always) || always) {
10482 // We left the provider in the launching list, need to
10483 // restart it.
10484 restart = true;
10485 }
10486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010487 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010488 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010489 }
10490 app.pubProviders.clear();
10491 }
10492
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010493 // Take care of any launching providers waiting for this process.
10494 if (checkAppInLaunchingProvidersLocked(app, false)) {
10495 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010496 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010498 // Unregister from connected content providers.
10499 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010500 for (int i=0; i<app.conProviders.size(); i++) {
10501 ContentProviderConnection conn = app.conProviders.get(i);
10502 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010503 }
10504 app.conProviders.clear();
10505 }
10506
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010507 // At this point there may be remaining entries in mLaunchingProviders
10508 // where we were the only one waiting, so they are no longer of use.
10509 // Look for these and clean up if found.
10510 // XXX Commented out for now. Trying to figure out a way to reproduce
10511 // the actual situation to identify what is actually going on.
10512 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010513 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010514 ContentProviderRecord cpr = (ContentProviderRecord)
10515 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010516 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010517 synchronized (cpr) {
10518 cpr.launchingApp = null;
10519 cpr.notifyAll();
10520 }
10521 }
10522 }
10523 }
10524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010525 skipCurrentReceiverLocked(app);
10526
10527 // Unregister any receivers.
10528 if (app.receivers.size() > 0) {
10529 Iterator<ReceiverList> it = app.receivers.iterator();
10530 while (it.hasNext()) {
10531 removeReceiverLocked(it.next());
10532 }
10533 app.receivers.clear();
10534 }
10535
Christopher Tate181fafa2009-05-14 11:12:14 -070010536 // If the app is undergoing backup, tell the backup manager about it
10537 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010538 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010539 try {
10540 IBackupManager bm = IBackupManager.Stub.asInterface(
10541 ServiceManager.getService(Context.BACKUP_SERVICE));
10542 bm.agentDisconnected(app.info.packageName);
10543 } catch (RemoteException e) {
10544 // can't happen; backup manager is local
10545 }
10546 }
10547
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010548 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10549 ProcessChangeItem item = mPendingProcessChanges.get(i);
10550 if (item.pid == app.pid) {
10551 mPendingProcessChanges.remove(i);
10552 mAvailProcessChanges.add(item);
10553 }
10554 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010555 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010557 // If the caller is restarting this app, then leave it in its
10558 // current lists and let the caller take care of it.
10559 if (restarting) {
10560 return;
10561 }
10562
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010563 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010564 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010565 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010566 mProcessNames.remove(app.processName, app.uid);
10567 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010568 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010569 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10570 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010571 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010573 } else if (!app.removed) {
10574 // This app is persistent, so we need to keep its record around.
10575 // If it is not already on the pending app list, add it there
10576 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010577 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10578 mPersistentStartingProcesses.add(app);
10579 restart = true;
10580 }
10581 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010582 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10583 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010584 mProcessesOnHold.remove(app);
10585
The Android Open Source Project4df24232009-03-05 14:34:35 -080010586 if (app == mHomeProcess) {
10587 mHomeProcess = null;
10588 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010589 if (app == mPreviousProcess) {
10590 mPreviousProcess = null;
10591 }
10592
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010593 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010594 // We have components that still need to be running in the
10595 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010596 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010597 startProcessLocked(app, "restart", app.processName);
10598 } else if (app.pid > 0 && app.pid != MY_PID) {
10599 // Goodbye!
10600 synchronized (mPidsSelfLocked) {
10601 mPidsSelfLocked.remove(app.pid);
10602 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10603 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010604 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010605 }
10606 }
10607
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010608 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10609 // Look through the content providers we are waiting to have launched,
10610 // and if any run in this process then either schedule a restart of
10611 // the process or kill the client waiting for it if this process has
10612 // gone bad.
10613 int NL = mLaunchingProviders.size();
10614 boolean restart = false;
10615 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010616 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010617 if (cpr.launchingApp == app) {
10618 if (!alwaysBad && !app.bad) {
10619 restart = true;
10620 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010621 removeDyingProviderLocked(app, cpr, true);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010622 NL = mLaunchingProviders.size();
10623 }
10624 }
10625 }
10626 return restart;
10627 }
10628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010629 // =========================================================
10630 // SERVICES
10631 // =========================================================
10632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010633 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10634 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010635 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010636 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010637 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010638 }
10639 }
10640
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010641 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010642 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010643 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010644 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010645 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010646 }
10647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010648 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010649 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010650 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010651 // Refuse possible leaked file descriptors
10652 if (service != null && service.hasFileDescriptors() == true) {
10653 throw new IllegalArgumentException("File descriptors passed in Intent");
10654 }
10655
Amith Yamasani742a6712011-05-04 14:49:28 -070010656 if (DEBUG_SERVICE)
10657 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010658 synchronized(this) {
10659 final int callingPid = Binder.getCallingPid();
10660 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010661 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010662 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010663 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010664 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010665 Binder.restoreCallingIdentity(origId);
10666 return res;
10667 }
10668 }
10669
10670 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010671 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010672 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010673 if (DEBUG_SERVICE)
10674 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010675 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010676 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010677 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010678 Binder.restoreCallingIdentity(origId);
10679 return res;
10680 }
10681 }
10682
10683 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010684 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010685 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010686 // Refuse possible leaked file descriptors
10687 if (service != null && service.hasFileDescriptors() == true) {
10688 throw new IllegalArgumentException("File descriptors passed in Intent");
10689 }
10690
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010691 checkValidCaller(Binder.getCallingUid(), userId);
10692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010693 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010694 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010696 }
10697
10698 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010699 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010700 // Refuse possible leaked file descriptors
10701 if (service != null && service.hasFileDescriptors() == true) {
10702 throw new IllegalArgumentException("File descriptors passed in Intent");
10703 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010704 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010705 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010707 }
10708
10709 public boolean stopServiceToken(ComponentName className, IBinder token,
10710 int startId) {
10711 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010712 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010714 }
10715
10716 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010717 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010718 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010719 mServices.setServiceForegroundLocked(className, token, id, notification,
10720 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010721 }
10722 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010723
Dianne Hackborn41203752012-08-31 14:05:51 -070010724 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10725 boolean requireFull, String name, String callerPackage) {
10726 synchronized(this) {
10727 return handleIncomingUserLocked(callingPid, callingUid, userId, allowAll,
10728 requireFull, name, callerPackage);
10729 }
10730 }
10731
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010732 int handleIncomingUserLocked(int callingPid, int callingUid, int userId, boolean allowAll,
10733 boolean requireFull, String name, String callerPackage) {
10734 final int callingUserId = UserHandle.getUserId(callingUid);
10735 if (callingUserId != userId) {
10736 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10737 if ((requireFull || checkComponentPermission(
10738 android.Manifest.permission.INTERACT_ACROSS_USERS,
10739 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10740 && checkComponentPermission(
10741 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10742 callingPid, callingUid, -1, true)
10743 != PackageManager.PERMISSION_GRANTED) {
10744 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10745 // In this case, they would like to just execute as their
10746 // owner user instead of failing.
10747 userId = callingUserId;
10748 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010749 StringBuilder builder = new StringBuilder(128);
10750 builder.append("Permission Denial: ");
10751 builder.append(name);
10752 if (callerPackage != null) {
10753 builder.append(" from ");
10754 builder.append(callerPackage);
10755 }
10756 builder.append(" asks to run as user ");
10757 builder.append(userId);
10758 builder.append(" but is calling from user ");
10759 builder.append(UserHandle.getUserId(callingUid));
10760 builder.append("; this requires ");
10761 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10762 if (!requireFull) {
10763 builder.append("or");
10764 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10765 }
10766 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010767 Slog.w(TAG, msg);
10768 throw new SecurityException(msg);
10769 }
10770 }
10771 }
10772 if (userId == UserHandle.USER_CURRENT
10773 || userId == UserHandle.USER_CURRENT_OR_SELF) {
10774 userId = mCurrentUserId;
10775 }
10776 if (!allowAll && userId < 0) {
10777 throw new IllegalArgumentException(
10778 "Call does not support special user #" + userId);
10779 }
10780 }
10781 return userId;
10782 }
10783
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010784 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10785 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010786 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010787 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010788 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10789 if (ActivityManager.checkUidPermission(
10790 android.Manifest.permission.INTERACT_ACROSS_USERS,
10791 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10792 ComponentName comp = new ComponentName(aInfo.packageName, className);
10793 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10794 + " requests FLAG_SINGLE_USER, but app does not hold "
10795 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10796 Slog.w(TAG, msg);
10797 throw new SecurityException(msg);
10798 }
10799 result = true;
10800 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010801 } else if (componentProcessName == aInfo.packageName) {
10802 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10803 } else if ("system".equals(componentProcessName)) {
10804 result = true;
10805 }
10806 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010807 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10808 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010809 }
10810 return result;
10811 }
10812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010813 public int bindService(IApplicationThread caller, IBinder token,
10814 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010815 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010816 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010817 // Refuse possible leaked file descriptors
10818 if (service != null && service.hasFileDescriptors() == true) {
10819 throw new IllegalArgumentException("File descriptors passed in Intent");
10820 }
10821
10822 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010823 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10824 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010825 }
10826 }
10827
10828 public boolean unbindService(IServiceConnection connection) {
10829 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010830 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010832 }
10833
10834 public void publishService(IBinder token, Intent intent, IBinder service) {
10835 // Refuse possible leaked file descriptors
10836 if (intent != null && intent.hasFileDescriptors() == true) {
10837 throw new IllegalArgumentException("File descriptors passed in Intent");
10838 }
10839
10840 synchronized(this) {
10841 if (!(token instanceof ServiceRecord)) {
10842 throw new IllegalArgumentException("Invalid service token");
10843 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010844 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010845 }
10846 }
10847
10848 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10849 // Refuse possible leaked file descriptors
10850 if (intent != null && intent.hasFileDescriptors() == true) {
10851 throw new IllegalArgumentException("File descriptors passed in Intent");
10852 }
10853
10854 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010855 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010856 }
10857 }
10858
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010859 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010860 synchronized(this) {
10861 if (!(token instanceof ServiceRecord)) {
10862 throw new IllegalArgumentException("Invalid service token");
10863 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010864 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010866 }
10867
10868 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010869 // BACKUP AND RESTORE
10870 // =========================================================
10871
10872 // Cause the target app to be launched if necessary and its backup agent
10873 // instantiated. The backup agent will invoke backupAgentCreated() on the
10874 // activity manager to announce its creation.
10875 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010876 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010877 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10878
10879 synchronized(this) {
10880 // !!! TODO: currently no check here that we're already bound
10881 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10882 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10883 synchronized (stats) {
10884 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10885 }
10886
Dianne Hackborne7f97212011-02-24 14:40:20 -080010887 // Backup agent is now in use, its package can't be stopped.
10888 try {
10889 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010890 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080010891 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010892 } catch (IllegalArgumentException e) {
10893 Slog.w(TAG, "Failed trying to unstop package "
10894 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010895 }
10896
Christopher Tate181fafa2009-05-14 11:12:14 -070010897 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070010898 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
10899 ? new ComponentName(app.packageName, app.backupAgentName)
10900 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070010901 // startProcessLocked() returns existing proc's record if it's already running
10902 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010903 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010904 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010905 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010906 return false;
10907 }
10908
10909 r.app = proc;
10910 mBackupTarget = r;
10911 mBackupAppName = app.packageName;
10912
Christopher Tate6fa95972009-06-05 18:43:55 -070010913 // Try not to kill the process during backup
10914 updateOomAdjLocked(proc);
10915
Christopher Tate181fafa2009-05-14 11:12:14 -070010916 // If the process is already attached, schedule the creation of the backup agent now.
10917 // If it is not yet live, this will be done when it attaches to the framework.
10918 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010919 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070010920 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010921 proc.thread.scheduleCreateBackupAgent(app,
10922 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010923 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070010924 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070010925 }
10926 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010927 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070010928 }
10929 // Invariants: at this point, the target app process exists and the application
10930 // is either already running or in the process of coming up. mBackupTarget and
10931 // mBackupAppName describe the app, so that when it binds back to the AM we
10932 // know that it's scheduled for a backup-agent operation.
10933 }
10934
10935 return true;
10936 }
10937
10938 // A backup agent has just come up
10939 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010940 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070010941 + " = " + agent);
10942
10943 synchronized(this) {
10944 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010945 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070010946 return;
10947 }
Dianne Hackborn06740692010-09-22 22:46:21 -070010948 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010949
Dianne Hackborn06740692010-09-22 22:46:21 -070010950 long oldIdent = Binder.clearCallingIdentity();
10951 try {
10952 IBackupManager bm = IBackupManager.Stub.asInterface(
10953 ServiceManager.getService(Context.BACKUP_SERVICE));
10954 bm.agentConnected(agentPackageName, agent);
10955 } catch (RemoteException e) {
10956 // can't happen; the backup manager service is local
10957 } catch (Exception e) {
10958 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
10959 e.printStackTrace();
10960 } finally {
10961 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070010962 }
10963 }
10964
10965 // done with this agent
10966 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010967 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070010968 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010969 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070010970 return;
10971 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010972
10973 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070010974 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010975 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070010976 return;
10977 }
10978
Christopher Tate181fafa2009-05-14 11:12:14 -070010979 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010980 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070010981 return;
10982 }
10983
Christopher Tate6fa95972009-06-05 18:43:55 -070010984 ProcessRecord proc = mBackupTarget.app;
10985 mBackupTarget = null;
10986 mBackupAppName = null;
10987
10988 // Not backing this app up any more; reset its OOM adjustment
10989 updateOomAdjLocked(proc);
10990
Christopher Tatec7b31e32009-06-10 15:49:30 -070010991 // If the app crashed during backup, 'thread' will be null here
10992 if (proc.thread != null) {
10993 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010994 proc.thread.scheduleDestroyBackupAgent(appInfo,
10995 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070010996 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010997 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070010998 e.printStackTrace();
10999 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011000 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011001 }
11002 }
11003 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011004 // BROADCASTS
11005 // =========================================================
11006
Josh Bartel7f208742010-02-25 11:01:44 -060011007 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011008 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011009 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011010 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11011 if (stickies == null) {
11012 return cur;
11013 }
11014 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011015 if (list == null) {
11016 return cur;
11017 }
11018 int N = list.size();
11019 for (int i=0; i<N; i++) {
11020 Intent intent = list.get(i);
11021 if (filter.match(resolver, intent, true, TAG) >= 0) {
11022 if (cur == null) {
11023 cur = new ArrayList<Intent>();
11024 }
11025 cur.add(intent);
11026 }
11027 }
11028 return cur;
11029 }
11030
Christopher Tatef46723b2012-01-26 14:19:24 -080011031 boolean isPendingBroadcastProcessLocked(int pid) {
11032 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11033 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011035
Christopher Tatef46723b2012-01-26 14:19:24 -080011036 void skipPendingBroadcastLocked(int pid) {
11037 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11038 for (BroadcastQueue queue : mBroadcastQueues) {
11039 queue.skipPendingBroadcastLocked(pid);
11040 }
11041 }
11042
11043 // The app just attached; send any pending broadcasts that it should receive
11044 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11045 boolean didSomething = false;
11046 for (BroadcastQueue queue : mBroadcastQueues) {
11047 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011048 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011049 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011050 }
11051
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011052 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011053 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011054 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011055 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011056 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011057 synchronized(this) {
11058 ProcessRecord callerApp = null;
11059 if (caller != null) {
11060 callerApp = getRecordForAppLocked(caller);
11061 if (callerApp == null) {
11062 throw new SecurityException(
11063 "Unable to find app for caller " + caller
11064 + " (pid=" + Binder.getCallingPid()
11065 + ") when registering receiver " + receiver);
11066 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011067 if (callerApp.info.uid != Process.SYSTEM_UID &&
11068 !callerApp.pkgList.contains(callerPackage)) {
11069 throw new SecurityException("Given caller package " + callerPackage
11070 + " is not running in process " + callerApp);
11071 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011072 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011073 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011074 } else {
11075 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011076 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011077 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011078 }
11079
Dianne Hackborn20e80982012-08-31 19:00:44 -070011080 userId = this.handleIncomingUserLocked(callingPid, callingUid, userId,
11081 true, true, "registerReceiver", callerPackage);
11082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011083 List allSticky = null;
11084
11085 // Look for any matching sticky broadcasts...
11086 Iterator actions = filter.actionsIterator();
11087 if (actions != null) {
11088 while (actions.hasNext()) {
11089 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011090 allSticky = getStickiesLocked(action, filter, allSticky,
11091 UserHandle.USER_ALL);
11092 allSticky = getStickiesLocked(action, filter, allSticky,
11093 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011094 }
11095 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011096 allSticky = getStickiesLocked(null, filter, allSticky,
11097 UserHandle.USER_ALL);
11098 allSticky = getStickiesLocked(null, filter, allSticky,
11099 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011100 }
11101
11102 // The first sticky in the list is returned directly back to
11103 // the client.
11104 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11105
Joe Onorato8a9b2202010-02-26 18:56:32 -080011106 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011107 + ": " + sticky);
11108
11109 if (receiver == null) {
11110 return sticky;
11111 }
11112
11113 ReceiverList rl
11114 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11115 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011116 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11117 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011118 if (rl.app != null) {
11119 rl.app.receivers.add(rl);
11120 } else {
11121 try {
11122 receiver.asBinder().linkToDeath(rl, 0);
11123 } catch (RemoteException e) {
11124 return sticky;
11125 }
11126 rl.linkedToDeath = true;
11127 }
11128 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011129 } else if (rl.uid != callingUid) {
11130 throw new IllegalArgumentException(
11131 "Receiver requested to register for uid " + callingUid
11132 + " was previously registered for uid " + rl.uid);
11133 } else if (rl.pid != callingPid) {
11134 throw new IllegalArgumentException(
11135 "Receiver requested to register for pid " + callingPid
11136 + " was previously registered for pid " + rl.pid);
11137 } else if (rl.userId != userId) {
11138 throw new IllegalArgumentException(
11139 "Receiver requested to register for user " + userId
11140 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011141 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011142 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011143 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011144 rl.add(bf);
11145 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011146 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011147 }
11148 mReceiverResolver.addFilter(bf);
11149
11150 // Enqueue broadcasts for all existing stickies that match
11151 // this filter.
11152 if (allSticky != null) {
11153 ArrayList receivers = new ArrayList();
11154 receivers.add(bf);
11155
11156 int N = allSticky.size();
11157 for (int i=0; i<N; i++) {
11158 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011159 BroadcastQueue queue = broadcastQueueForIntent(intent);
11160 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011161 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011162 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011163 queue.enqueueParallelBroadcastLocked(r);
11164 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011165 }
11166 }
11167
11168 return sticky;
11169 }
11170 }
11171
11172 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011173 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011174
Christopher Tatef46723b2012-01-26 14:19:24 -080011175 final long origId = Binder.clearCallingIdentity();
11176 try {
11177 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011178
Christopher Tatef46723b2012-01-26 14:19:24 -080011179 synchronized(this) {
11180 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011181 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011182 if (rl != null) {
11183 if (rl.curBroadcast != null) {
11184 BroadcastRecord r = rl.curBroadcast;
11185 final boolean doNext = finishReceiverLocked(
11186 receiver.asBinder(), r.resultCode, r.resultData,
11187 r.resultExtras, r.resultAbort, true);
11188 if (doNext) {
11189 doTrim = true;
11190 r.queue.processNextBroadcast(false);
11191 }
11192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011193
Christopher Tatef46723b2012-01-26 14:19:24 -080011194 if (rl.app != null) {
11195 rl.app.receivers.remove(rl);
11196 }
11197 removeReceiverLocked(rl);
11198 if (rl.linkedToDeath) {
11199 rl.linkedToDeath = false;
11200 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011202 }
11203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011204
Christopher Tatef46723b2012-01-26 14:19:24 -080011205 // If we actually concluded any broadcasts, we might now be able
11206 // to trim the recipients' apps from our working set
11207 if (doTrim) {
11208 trimApplications();
11209 return;
11210 }
11211
11212 } finally {
11213 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011215 }
11216
11217 void removeReceiverLocked(ReceiverList rl) {
11218 mRegisteredReceivers.remove(rl.receiver.asBinder());
11219 int N = rl.size();
11220 for (int i=0; i<N; i++) {
11221 mReceiverResolver.removeFilter(rl.get(i));
11222 }
11223 }
11224
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011225 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011226 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11227 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011228 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011229 try {
11230 r.thread.dispatchPackageBroadcast(cmd, packages);
11231 } catch (RemoteException ex) {
11232 }
11233 }
11234 }
11235 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011236
11237 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11238 int[] users) {
11239 List<ResolveInfo> receivers = null;
11240 try {
11241 HashSet<ComponentName> singleUserReceivers = null;
11242 boolean scannedFirstReceivers = false;
11243 for (int user : users) {
11244 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11245 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
11246 if (newReceivers != null && newReceivers.size() == 0) {
11247 newReceivers = null;
11248 }
11249 if (receivers == null) {
11250 receivers = newReceivers;
11251 } else if (newReceivers != null) {
11252 // We need to concatenate the additional receivers
11253 // found with what we have do far. This would be easy,
11254 // but we also need to de-dup any receivers that are
11255 // singleUser.
11256 if (!scannedFirstReceivers) {
11257 // Collect any single user receivers we had already retrieved.
11258 scannedFirstReceivers = true;
11259 for (int i=0; i<receivers.size(); i++) {
11260 ResolveInfo ri = receivers.get(i);
11261 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11262 ComponentName cn = new ComponentName(
11263 ri.activityInfo.packageName, ri.activityInfo.name);
11264 if (singleUserReceivers == null) {
11265 singleUserReceivers = new HashSet<ComponentName>();
11266 }
11267 singleUserReceivers.add(cn);
11268 }
11269 }
11270 }
11271 // Add the new results to the existing results, tracking
11272 // and de-dupping single user receivers.
11273 for (int i=0; i<newReceivers.size(); i++) {
11274 ResolveInfo ri = receivers.get(i);
11275 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11276 ComponentName cn = new ComponentName(
11277 ri.activityInfo.packageName, ri.activityInfo.name);
11278 if (singleUserReceivers == null) {
11279 singleUserReceivers = new HashSet<ComponentName>();
11280 }
11281 if (!singleUserReceivers.contains(cn)) {
11282 singleUserReceivers.add(cn);
11283 receivers.add(ri);
11284 }
11285 } else {
11286 receivers.add(ri);
11287 }
11288 }
11289 }
11290 }
11291 } catch (RemoteException ex) {
11292 // pm is in same process, this will never happen.
11293 }
11294 return receivers;
11295 }
11296
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011297 private final int broadcastIntentLocked(ProcessRecord callerApp,
11298 String callerPackage, Intent intent, String resolvedType,
11299 IIntentReceiver resultTo, int resultCode, String resultData,
11300 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011301 boolean ordered, boolean sticky, int callingPid, int callingUid,
11302 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011303 intent = new Intent(intent);
11304
Dianne Hackborne7f97212011-02-24 14:40:20 -080011305 // By default broadcasts do not go to stopped apps.
11306 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11307
Joe Onorato8a9b2202010-02-26 18:56:32 -080011308 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011309 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011310 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011311 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011312 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011313 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011314
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011315 userId = handleIncomingUserLocked(callingPid, callingUid, userId,
11316 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011317
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011318 // Make sure that the user who is receiving this broadcast is started
11319 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011320 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011321 Slog.w(TAG, "Skipping broadcast of " + intent
11322 + ": user " + userId + " is stopped");
11323 return ActivityManager.BROADCAST_SUCCESS;
11324 }
11325
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011326 /*
11327 * Prevent non-system code (defined here to be non-persistent
11328 * processes) from sending protected broadcasts.
11329 */
11330 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11331 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11332 callingUid == 0) {
11333 // Always okay.
11334 } else if (callerApp == null || !callerApp.persistent) {
11335 try {
11336 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11337 intent.getAction())) {
11338 String msg = "Permission Denial: not allowed to send broadcast "
11339 + intent.getAction() + " from pid="
11340 + callingPid + ", uid=" + callingUid;
11341 Slog.w(TAG, msg);
11342 throw new SecurityException(msg);
11343 }
11344 } catch (RemoteException e) {
11345 Slog.w(TAG, "Remote exception", e);
11346 return ActivityManager.BROADCAST_SUCCESS;
11347 }
11348 }
11349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011350 // Handle special intents: if this broadcast is from the package
11351 // manager about a package being removed, we need to remove all of
11352 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011353 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011354 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011355 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11356 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011357 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011358 || uidRemoved) {
11359 if (checkComponentPermission(
11360 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011361 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011362 == PackageManager.PERMISSION_GRANTED) {
11363 if (uidRemoved) {
11364 final Bundle intentExtras = intent.getExtras();
11365 final int uid = intentExtras != null
11366 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11367 if (uid >= 0) {
11368 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11369 synchronized (bs) {
11370 bs.removeUidStatsLocked(uid);
11371 }
11372 }
11373 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011374 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011375 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011376 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011377 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11378 if (list != null && (list.length > 0)) {
11379 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011380 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011381 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011382 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011383 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011384 }
11385 } else {
11386 Uri data = intent.getData();
11387 String ssp;
11388 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11389 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11390 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011391 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11392 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011393 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011394 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011395 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011396 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011397 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011398 }
11399 }
11400 }
11401 } else {
11402 String msg = "Permission Denial: " + intent.getAction()
11403 + " broadcast from " + callerPackage + " (pid=" + callingPid
11404 + ", uid=" + callingUid + ")"
11405 + " requires "
11406 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011407 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011408 throw new SecurityException(msg);
11409 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011410
11411 // Special case for adding a package: by default turn on compatibility
11412 // mode.
11413 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011414 Uri data = intent.getData();
11415 String ssp;
11416 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11417 mCompatModePackages.handlePackageAddedLocked(ssp,
11418 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011420 }
11421
11422 /*
11423 * If this is the time zone changed action, queue up a message that will reset the timezone
11424 * of all currently running processes. This message will get queued up before the broadcast
11425 * happens.
11426 */
11427 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11428 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11429 }
11430
Robert Greenwalt03595d02010-11-02 14:08:23 -070011431 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11432 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11433 }
11434
Robert Greenwalt434203a2010-10-11 16:00:27 -070011435 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11436 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11437 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11438 }
11439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011440 // Add to the sticky list if requested.
11441 if (sticky) {
11442 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11443 callingPid, callingUid)
11444 != PackageManager.PERMISSION_GRANTED) {
11445 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11446 + callingPid + ", uid=" + callingUid
11447 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011448 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 throw new SecurityException(msg);
11450 }
11451 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011452 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011454 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011455 }
11456 if (intent.getComponent() != null) {
11457 throw new SecurityException(
11458 "Sticky broadcasts can't target a specific component");
11459 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011460 // We use userId directly here, since the "all" target is maintained
11461 // as a separate set of sticky broadcasts.
11462 if (userId != UserHandle.USER_ALL) {
11463 // But first, if this is not a broadcast to all users, then
11464 // make sure it doesn't conflict with an existing broadcast to
11465 // all users.
11466 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11467 UserHandle.USER_ALL);
11468 if (stickies != null) {
11469 ArrayList<Intent> list = stickies.get(intent.getAction());
11470 if (list != null) {
11471 int N = list.size();
11472 int i;
11473 for (i=0; i<N; i++) {
11474 if (intent.filterEquals(list.get(i))) {
11475 throw new IllegalArgumentException(
11476 "Sticky broadcast " + intent + " for user "
11477 + userId + " conflicts with existing global broadcast");
11478 }
11479 }
11480 }
11481 }
11482 }
11483 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11484 if (stickies == null) {
11485 stickies = new HashMap<String, ArrayList<Intent>>();
11486 mStickyBroadcasts.put(userId, stickies);
11487 }
11488 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011489 if (list == null) {
11490 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011491 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011492 }
11493 int N = list.size();
11494 int i;
11495 for (i=0; i<N; i++) {
11496 if (intent.filterEquals(list.get(i))) {
11497 // This sticky already exists, replace it.
11498 list.set(i, new Intent(intent));
11499 break;
11500 }
11501 }
11502 if (i >= N) {
11503 list.add(new Intent(intent));
11504 }
11505 }
11506
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011507 int[] users;
11508 if (userId == UserHandle.USER_ALL) {
11509 // Caller wants broadcast to go to all started users.
11510 users = new int[mStartedUsers.size()];
11511 for (int i=0; i<mStartedUsers.size(); i++) {
11512 users[i] = mStartedUsers.keyAt(i);
11513 }
11514 } else {
11515 // Caller wants broadcast to go to one specific user.
11516 users = new int[] {userId};
11517 }
11518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011519 // Figure out who all will receive this broadcast.
11520 List receivers = null;
11521 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011522 // Need to resolve the intent to interested receivers...
11523 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11524 == 0) {
11525 receivers = collectReceiverComponents(intent, resolvedType, users);
11526 }
11527 if (intent.getComponent() == null) {
11528 registeredReceivers = mReceiverResolver.queryIntent(intent,
11529 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011530 }
11531
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011532 final boolean replacePending =
11533 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11534
Joe Onorato8a9b2202010-02-26 18:56:32 -080011535 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011536 + " replacePending=" + replacePending);
11537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011538 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11539 if (!ordered && NR > 0) {
11540 // If we are not serializing this broadcast, then send the
11541 // registered receivers separately so they don't wait for the
11542 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011543 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11544 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011545 callerPackage, callingPid, callingUid, requiredPermission,
11546 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011547 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011548 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011549 TAG, "Enqueueing parallel broadcast " + r);
11550 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011551 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011552 queue.enqueueParallelBroadcastLocked(r);
11553 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011555 registeredReceivers = null;
11556 NR = 0;
11557 }
11558
11559 // Merge into one list.
11560 int ir = 0;
11561 if (receivers != null) {
11562 // A special case for PACKAGE_ADDED: do not allow the package
11563 // being added to see this broadcast. This prevents them from
11564 // using this as a back door to get run as soon as they are
11565 // installed. Maybe in the future we want to have a special install
11566 // broadcast or such for apps, but we'd like to deliberately make
11567 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011568 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011569 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11570 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11571 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011572 Uri data = intent.getData();
11573 if (data != null) {
11574 String pkgName = data.getSchemeSpecificPart();
11575 if (pkgName != null) {
11576 skipPackages = new String[] { pkgName };
11577 }
11578 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011579 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011580 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011581 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011582 if (skipPackages != null && (skipPackages.length > 0)) {
11583 for (String skipPackage : skipPackages) {
11584 if (skipPackage != null) {
11585 int NT = receivers.size();
11586 for (int it=0; it<NT; it++) {
11587 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11588 if (curt.activityInfo.packageName.equals(skipPackage)) {
11589 receivers.remove(it);
11590 it--;
11591 NT--;
11592 }
11593 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011594 }
11595 }
11596 }
11597
11598 int NT = receivers != null ? receivers.size() : 0;
11599 int it = 0;
11600 ResolveInfo curt = null;
11601 BroadcastFilter curr = null;
11602 while (it < NT && ir < NR) {
11603 if (curt == null) {
11604 curt = (ResolveInfo)receivers.get(it);
11605 }
11606 if (curr == null) {
11607 curr = registeredReceivers.get(ir);
11608 }
11609 if (curr.getPriority() >= curt.priority) {
11610 // Insert this broadcast record into the final list.
11611 receivers.add(it, curr);
11612 ir++;
11613 curr = null;
11614 it++;
11615 NT++;
11616 } else {
11617 // Skip to the next ResolveInfo in the final list.
11618 it++;
11619 curt = null;
11620 }
11621 }
11622 }
11623 while (ir < NR) {
11624 if (receivers == null) {
11625 receivers = new ArrayList();
11626 }
11627 receivers.add(registeredReceivers.get(ir));
11628 ir++;
11629 }
11630
11631 if ((receivers != null && receivers.size() > 0)
11632 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011633 BroadcastQueue queue = broadcastQueueForIntent(intent);
11634 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011635 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011636 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011637 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011638 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011639 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011640 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011641 if (DEBUG_BROADCAST) {
11642 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011643 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011644 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011645 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011646 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011647 queue.enqueueOrderedBroadcastLocked(r);
11648 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011650 }
11651
Dianne Hackborna4972e92012-03-14 10:38:05 -070011652 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011653 }
11654
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011655 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011656 // Refuse possible leaked file descriptors
11657 if (intent != null && intent.hasFileDescriptors() == true) {
11658 throw new IllegalArgumentException("File descriptors passed in Intent");
11659 }
11660
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011661 int flags = intent.getFlags();
11662
11663 if (!mProcessesReady) {
11664 // if the caller really truly claims to know what they're doing, go
11665 // ahead and allow the broadcast without launching any receivers
11666 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11667 intent = new Intent(intent);
11668 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11669 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11670 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11671 + " before boot completion");
11672 throw new IllegalStateException("Cannot broadcast before boot completed");
11673 }
11674 }
11675
11676 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11677 throw new IllegalArgumentException(
11678 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11679 }
11680
11681 return intent;
11682 }
11683
11684 public final int broadcastIntent(IApplicationThread caller,
11685 Intent intent, String resolvedType, IIntentReceiver resultTo,
11686 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011687 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011688 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011689 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011690 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011692 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11693 final int callingPid = Binder.getCallingPid();
11694 final int callingUid = Binder.getCallingUid();
11695 final long origId = Binder.clearCallingIdentity();
11696 int res = broadcastIntentLocked(callerApp,
11697 callerApp != null ? callerApp.info.packageName : null,
11698 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011699 resultCode, resultData, map, requiredPermission, serialized, sticky,
11700 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011701 Binder.restoreCallingIdentity(origId);
11702 return res;
11703 }
11704 }
11705
11706 int broadcastIntentInPackage(String packageName, int uid,
11707 Intent intent, String resolvedType, IIntentReceiver resultTo,
11708 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011709 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011710 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011711 intent = verifyBroadcastLocked(intent);
11712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011713 final long origId = Binder.clearCallingIdentity();
11714 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11715 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011716 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011717 Binder.restoreCallingIdentity(origId);
11718 return res;
11719 }
11720 }
11721
Amith Yamasani742a6712011-05-04 14:49:28 -070011722 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011723 // Refuse possible leaked file descriptors
11724 if (intent != null && intent.hasFileDescriptors() == true) {
11725 throw new IllegalArgumentException("File descriptors passed in Intent");
11726 }
11727
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011728 userId = handleIncomingUserLocked(Binder.getCallingPid(),
11729 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011731 synchronized(this) {
11732 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11733 != PackageManager.PERMISSION_GRANTED) {
11734 String msg = "Permission Denial: unbroadcastIntent() from pid="
11735 + Binder.getCallingPid()
11736 + ", uid=" + Binder.getCallingUid()
11737 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011738 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011739 throw new SecurityException(msg);
11740 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011741 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11742 if (stickies != null) {
11743 ArrayList<Intent> list = stickies.get(intent.getAction());
11744 if (list != null) {
11745 int N = list.size();
11746 int i;
11747 for (i=0; i<N; i++) {
11748 if (intent.filterEquals(list.get(i))) {
11749 list.remove(i);
11750 break;
11751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011752 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011753 if (list.size() <= 0) {
11754 stickies.remove(intent.getAction());
11755 }
11756 }
11757 if (stickies.size() <= 0) {
11758 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011759 }
11760 }
11761 }
11762 }
11763
11764 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11765 String resultData, Bundle resultExtras, boolean resultAbort,
11766 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011767 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11768 if (r == null) {
11769 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011770 return false;
11771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011772
Christopher Tatef46723b2012-01-26 14:19:24 -080011773 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11774 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011775 }
11776
11777 public void finishReceiver(IBinder who, int resultCode, String resultData,
11778 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011779 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011780
11781 // Refuse possible leaked file descriptors
11782 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11783 throw new IllegalArgumentException("File descriptors passed in Bundle");
11784 }
11785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011786 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011787 try {
11788 boolean doNext = false;
11789 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011790
Christopher Tatef46723b2012-01-26 14:19:24 -080011791 synchronized(this) {
11792 r = broadcastRecordForReceiverLocked(who);
11793 if (r != null) {
11794 doNext = r.queue.finishReceiverLocked(r, resultCode,
11795 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011797 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011798
Christopher Tatef46723b2012-01-26 14:19:24 -080011799 if (doNext) {
11800 r.queue.processNextBroadcast(false);
11801 }
11802 trimApplications();
11803 } finally {
11804 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011808 // =========================================================
11809 // INSTRUMENTATION
11810 // =========================================================
11811
11812 public boolean startInstrumentation(ComponentName className,
11813 String profileFile, int flags, Bundle arguments,
11814 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011815 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011816 // Refuse possible leaked file descriptors
11817 if (arguments != null && arguments.hasFileDescriptors()) {
11818 throw new IllegalArgumentException("File descriptors passed in Bundle");
11819 }
11820
11821 synchronized(this) {
11822 InstrumentationInfo ii = null;
11823 ApplicationInfo ai = null;
11824 try {
11825 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011826 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011827 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011828 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011829 } catch (PackageManager.NameNotFoundException e) {
11830 }
11831 if (ii == null) {
11832 reportStartInstrumentationFailure(watcher, className,
11833 "Unable to find instrumentation info for: " + className);
11834 return false;
11835 }
11836 if (ai == null) {
11837 reportStartInstrumentationFailure(watcher, className,
11838 "Unable to find instrumentation target package: " + ii.targetPackage);
11839 return false;
11840 }
11841
11842 int match = mContext.getPackageManager().checkSignatures(
11843 ii.targetPackage, ii.packageName);
11844 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11845 String msg = "Permission Denial: starting instrumentation "
11846 + className + " from pid="
11847 + Binder.getCallingPid()
11848 + ", uid=" + Binder.getCallingPid()
11849 + " not allowed because package " + ii.packageName
11850 + " does not have a signature matching the target "
11851 + ii.targetPackage;
11852 reportStartInstrumentationFailure(watcher, className, msg);
11853 throw new SecurityException(msg);
11854 }
11855
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011856 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011857 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070011858 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070011859 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011860 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011861 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011862 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011863 app.instrumentationProfileFile = profileFile;
11864 app.instrumentationArguments = arguments;
11865 app.instrumentationWatcher = watcher;
11866 app.instrumentationResultClass = className;
11867 Binder.restoreCallingIdentity(origId);
11868 }
11869
11870 return true;
11871 }
11872
11873 /**
11874 * Report errors that occur while attempting to start Instrumentation. Always writes the
11875 * error to the logs, but if somebody is watching, send the report there too. This enables
11876 * the "am" command to report errors with more information.
11877 *
11878 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11879 * @param cn The component name of the instrumentation.
11880 * @param report The error report.
11881 */
11882 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11883 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011884 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011885 try {
11886 if (watcher != null) {
11887 Bundle results = new Bundle();
11888 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11889 results.putString("Error", report);
11890 watcher.instrumentationStatus(cn, -1, results);
11891 }
11892 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011893 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011894 }
11895 }
11896
11897 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
11898 if (app.instrumentationWatcher != null) {
11899 try {
11900 // NOTE: IInstrumentationWatcher *must* be oneway here
11901 app.instrumentationWatcher.instrumentationFinished(
11902 app.instrumentationClass,
11903 resultCode,
11904 results);
11905 } catch (RemoteException e) {
11906 }
11907 }
11908 app.instrumentationWatcher = null;
11909 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011910 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011911 app.instrumentationProfileFile = null;
11912 app.instrumentationArguments = null;
11913
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011914 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011915 }
11916
11917 public void finishInstrumentation(IApplicationThread target,
11918 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011919 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011920 // Refuse possible leaked file descriptors
11921 if (results != null && results.hasFileDescriptors()) {
11922 throw new IllegalArgumentException("File descriptors passed in Intent");
11923 }
11924
11925 synchronized(this) {
11926 ProcessRecord app = getRecordForAppLocked(target);
11927 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011928 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011929 return;
11930 }
11931 final long origId = Binder.clearCallingIdentity();
11932 finishInstrumentationLocked(app, resultCode, results);
11933 Binder.restoreCallingIdentity(origId);
11934 }
11935 }
11936
11937 // =========================================================
11938 // CONFIGURATION
11939 // =========================================================
11940
11941 public ConfigurationInfo getDeviceConfigurationInfo() {
11942 ConfigurationInfo config = new ConfigurationInfo();
11943 synchronized (this) {
11944 config.reqTouchScreen = mConfiguration.touchscreen;
11945 config.reqKeyboardType = mConfiguration.keyboard;
11946 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011947 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
11948 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011949 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
11950 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011951 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
11952 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011953 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
11954 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070011955 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011956 }
11957 return config;
11958 }
11959
11960 public Configuration getConfiguration() {
11961 Configuration ci;
11962 synchronized(this) {
11963 ci = new Configuration(mConfiguration);
11964 }
11965 return ci;
11966 }
11967
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011968 public void updatePersistentConfiguration(Configuration values) {
11969 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11970 "updateConfiguration()");
11971 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
11972 "updateConfiguration()");
11973 if (values == null) {
11974 throw new NullPointerException("Configuration must not be null");
11975 }
11976
11977 synchronized(this) {
11978 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080011979 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011980 Binder.restoreCallingIdentity(origId);
11981 }
11982 }
11983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011984 public void updateConfiguration(Configuration values) {
11985 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11986 "updateConfiguration()");
11987
11988 synchronized(this) {
11989 if (values == null && mWindowManager != null) {
11990 // sentinel: fetch the current configuration from the window manager
11991 values = mWindowManager.computeNewConfiguration();
11992 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070011993
11994 if (mWindowManager != null) {
11995 mProcessList.applyDisplaySize(mWindowManager);
11996 }
11997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011998 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011999 if (values != null) {
12000 Settings.System.clearConfiguration(values);
12001 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012002 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012003 Binder.restoreCallingIdentity(origId);
12004 }
12005 }
12006
12007 /**
12008 * Do either or both things: (1) change the current configuration, and (2)
12009 * make sure the given activity is running with the (now) current
12010 * configuration. Returns true if the activity has been left running, or
12011 * false if <var>starting</var> is being destroyed to match the new
12012 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012013 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012014 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012015 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012016 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012017 // do nothing if we are headless
12018 if (mHeadless) return true;
12019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012020 int changes = 0;
12021
12022 boolean kept = true;
12023
12024 if (values != null) {
12025 Configuration newConfig = new Configuration(mConfiguration);
12026 changes = newConfig.updateFrom(values);
12027 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012028 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012029 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012030 }
12031
Doug Zongker2bec3d42009-12-04 12:52:44 -080012032 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012033
Dianne Hackborn813075a62011-11-14 17:45:19 -080012034 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012035 saveLocaleLocked(values.locale,
12036 !values.locale.equals(mConfiguration.locale),
12037 values.userSetLocale);
12038 }
12039
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012040 mConfigurationSeq++;
12041 if (mConfigurationSeq <= 0) {
12042 mConfigurationSeq = 1;
12043 }
12044 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012045 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012046 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012047
12048 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012049
12050 // TODO: If our config changes, should we auto dismiss any currently
12051 // showing dialogs?
12052 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012053
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012054 AttributeCache ac = AttributeCache.instance();
12055 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012056 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012058
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012059 // Make sure all resources in our process are updated
12060 // right now, so that anyone who is going to retrieve
12061 // resource values after we return will be sure to get
12062 // the new ones. This is especially important during
12063 // boot, where the first config change needs to guarantee
12064 // all resources have that config before following boot
12065 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012066 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012067
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012068 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012069 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012070 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012071 mHandler.sendMessage(msg);
12072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012073
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012074 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12075 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012076 try {
12077 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012078 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012079 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012080 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012081 }
12082 } catch (Exception e) {
12083 }
12084 }
12085 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012086 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12087 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012088 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012089 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012090 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12091 broadcastIntentLocked(null, null,
12092 new Intent(Intent.ACTION_LOCALE_CHANGED),
12093 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012094 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012096 }
12097 }
12098
12099 if (changes != 0 && starting == null) {
12100 // If the configuration changed, and the caller is not already
12101 // in the process of starting an activity, then find the top
12102 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012103 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012104 }
12105
12106 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012107 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012108 // And we need to make sure at this point that all other activities
12109 // are made visible with the correct configuration.
12110 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012111 }
12112
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012113 if (values != null && mWindowManager != null) {
12114 mWindowManager.setNewConfiguration(mConfiguration);
12115 }
12116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012117 return kept;
12118 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012119
12120 /**
12121 * Decide based on the configuration whether we should shouw the ANR,
12122 * crash, etc dialogs. The idea is that if there is no affordnace to
12123 * press the on-screen buttons, we shouldn't show the dialog.
12124 *
12125 * A thought: SystemUI might also want to get told about this, the Power
12126 * dialog / global actions also might want different behaviors.
12127 */
12128 private static final boolean shouldShowDialogs(Configuration config) {
12129 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12130 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012132
12133 /**
12134 * Save the locale. You must be inside a synchronized (this) block.
12135 */
12136 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12137 if(isDiff) {
12138 SystemProperties.set("user.language", l.getLanguage());
12139 SystemProperties.set("user.region", l.getCountry());
12140 }
12141
12142 if(isPersist) {
12143 SystemProperties.set("persist.sys.language", l.getLanguage());
12144 SystemProperties.set("persist.sys.country", l.getCountry());
12145 SystemProperties.set("persist.sys.localevar", l.getVariant());
12146 }
12147 }
12148
Adam Powelldd8fab22012-03-22 17:47:27 -070012149 @Override
12150 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12151 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012152 return srec != null && srec.task.affinity != null &&
12153 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012154 }
12155
12156 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12157 Intent resultData) {
12158 ComponentName dest = destIntent.getComponent();
12159
12160 synchronized (this) {
12161 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012162 if (srec == null) {
12163 return false;
12164 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012165 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12166 final int start = history.indexOf(srec);
12167 if (start < 0) {
12168 // Current activity is not in history stack; do nothing.
12169 return false;
12170 }
12171 int finishTo = start - 1;
12172 ActivityRecord parent = null;
12173 boolean foundParentInTask = false;
12174 if (dest != null) {
12175 TaskRecord tr = srec.task;
12176 for (int i = start - 1; i >= 0; i--) {
12177 ActivityRecord r = history.get(i);
12178 if (tr != r.task) {
12179 // Couldn't find parent in the same task; stop at the one above this.
12180 // (Root of current task; in-app "home" behavior)
12181 // Always at least finish the current activity.
12182 finishTo = Math.min(start - 1, i + 1);
12183 parent = history.get(finishTo);
12184 break;
12185 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12186 r.info.name.equals(dest.getClassName())) {
12187 finishTo = i;
12188 parent = r;
12189 foundParentInTask = true;
12190 break;
12191 }
12192 }
12193 }
12194
12195 if (mController != null) {
12196 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12197 if (next != null) {
12198 // ask watcher if this is allowed
12199 boolean resumeOK = true;
12200 try {
12201 resumeOK = mController.activityResuming(next.packageName);
12202 } catch (RemoteException e) {
12203 mController = null;
12204 }
12205
12206 if (!resumeOK) {
12207 return false;
12208 }
12209 }
12210 }
12211 final long origId = Binder.clearCallingIdentity();
12212 for (int i = start; i > finishTo; i--) {
12213 ActivityRecord r = history.get(i);
12214 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
12215 "navigate-up");
12216 // Only return the supplied result for the first activity finished
12217 resultCode = Activity.RESULT_CANCELED;
12218 resultData = null;
12219 }
12220
12221 if (parent != null && foundParentInTask) {
12222 final int parentLaunchMode = parent.info.launchMode;
12223 final int destIntentFlags = destIntent.getFlags();
12224 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12225 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12226 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12227 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012228 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012229 } else {
12230 try {
12231 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012232 destIntent.getComponent(), 0, UserHandle.getCallingUserId());
Adam Powelldd8fab22012-03-22 17:47:27 -070012233 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12234 null, aInfo, parent.appToken, null,
12235 0, -1, parent.launchedFromUid, 0, null, true, null);
12236 foundParentInTask = res == ActivityManager.START_SUCCESS;
12237 } catch (RemoteException e) {
12238 foundParentInTask = false;
12239 }
12240 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
12241 resultData, "navigate-up");
12242 }
12243 }
12244 Binder.restoreCallingIdentity(origId);
12245 return foundParentInTask;
12246 }
12247 }
12248
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012249 public int getLaunchedFromUid(IBinder activityToken) {
12250 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12251 if (srec == null) {
12252 return -1;
12253 }
12254 return srec.launchedFromUid;
12255 }
12256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012257 // =========================================================
12258 // LIFETIME MANAGEMENT
12259 // =========================================================
12260
Christopher Tatef46723b2012-01-26 14:19:24 -080012261 // Returns which broadcast queue the app is the current [or imminent] receiver
12262 // on, or 'null' if the app is not an active broadcast recipient.
12263 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12264 BroadcastRecord r = app.curReceiver;
12265 if (r != null) {
12266 return r.queue;
12267 }
12268
12269 // It's not the current receiver, but it might be starting up to become one
12270 synchronized (this) {
12271 for (BroadcastQueue queue : mBroadcastQueues) {
12272 r = queue.mPendingBroadcast;
12273 if (r != null && r.curApp == app) {
12274 // found it; report which queue it's in
12275 return queue;
12276 }
12277 }
12278 }
12279
12280 return null;
12281 }
12282
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012283 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012284 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012285 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012286 // This adjustment has already been computed. If we are calling
12287 // from the top, we may have already computed our adjustment with
12288 // an earlier hidden adjustment that isn't really for us... if
12289 // so, use the new hidden adjustment.
12290 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012291 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
12292 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012293 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012294 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012295 }
12296
12297 if (app.thread == null) {
12298 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012299 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012300 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012301 }
12302
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012303 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12304 app.adjSource = null;
12305 app.adjTarget = null;
12306 app.empty = false;
12307 app.hidden = false;
12308
12309 final int activitiesSize = app.activities.size();
12310
Dianne Hackborn7d608422011-08-07 16:24:18 -070012311 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012312 // The max adjustment doesn't allow this app to be anything
12313 // below foreground, so it is not worth doing work for it.
12314 app.adjType = "fixed";
12315 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012316 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012317 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012318 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012319 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012320 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012321 // System process can do UI, and when they do we want to have
12322 // them trim their memory after the user leaves the UI. To
12323 // facilitate this, here we need to determine whether or not it
12324 // is currently showing UI.
12325 app.systemNoUi = true;
12326 if (app == TOP_APP) {
12327 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012328 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012329 } else if (activitiesSize > 0) {
12330 for (int j = 0; j < activitiesSize; j++) {
12331 final ActivityRecord r = app.activities.get(j);
12332 if (r.visible) {
12333 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012334 }
12335 if (r.app == app) {
12336 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012337 }
12338 }
12339 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012340 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012341 }
12342
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012343 app.keeping = false;
12344 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012345 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012346
The Android Open Source Project4df24232009-03-05 14:34:35 -080012347 // Determine the importance of the process, starting with most
12348 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012349 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012350 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012351 boolean foregroundActivities = false;
12352 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012353 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012354 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012355 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012356 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012357 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012358 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012359 foregroundActivities = true;
12360 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012361 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012362 } else if (app.instrumentationClass != null) {
12363 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012364 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012365 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012366 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012367 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012368 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012369 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012370 // counts as being in the foreground for OOM killer purposes.
12371 // It's placed in a sched group based on the nature of the
12372 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012373 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012374 schedGroup = (queue == mFgBroadcastQueue)
12375 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012376 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012377 } else if (app.executingServices.size() > 0) {
12378 // An app that is currently executing a service callback also
12379 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012380 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012381 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012382 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012383 } else {
12384 // Assume process is hidden (has activities); we will correct
12385 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012386 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012387 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012388 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012389 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012390 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012391
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012392 boolean hasStoppingActivities = false;
12393
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012394 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012395 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012396 for (int j = 0; j < activitiesSize; j++) {
12397 final ActivityRecord r = app.activities.get(j);
12398 if (r.visible) {
12399 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012400 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12401 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012402 app.adjType = "visible";
12403 }
12404 schedGroup = Process.THREAD_GROUP_DEFAULT;
12405 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012406 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012407 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012408 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012409 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012410 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12411 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012412 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012413 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012414 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012415 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012416 } else if (r.state == ActivityState.STOPPING) {
12417 // We will apply the actual adjustment later, because
12418 // we want to allow this process to immediately go through
12419 // any memory trimming that is in effect.
12420 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012421 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012422 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012423 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012424 if (r.app == app) {
12425 app.hasActivities = true;
12426 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012427 }
12428 }
12429
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012430 if (adj == hiddenAdj && !app.hasActivities) {
12431 // Whoops, this process is completely empty as far as we know
12432 // at this point.
12433 adj = emptyAdj;
12434 app.empty = true;
12435 app.adjType = "bg-empty";
12436 }
12437
Dianne Hackborn7d608422011-08-07 16:24:18 -070012438 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012439 if (app.foregroundServices) {
12440 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012441 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012442 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012443 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012444 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012445 } else if (app.forcingToForeground != null) {
12446 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012447 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012448 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012449 app.adjType = "force-foreground";
12450 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012451 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012452 }
12453 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012454
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012455 if (app.foregroundServices) {
12456 interesting = true;
12457 }
12458
Dianne Hackborn7d608422011-08-07 16:24:18 -070012459 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012460 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012461 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012462 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012463 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012464 app.adjType = "heavy";
12465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012466
Dianne Hackborn7d608422011-08-07 16:24:18 -070012467 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012468 // This process is hosting what we currently consider to be the
12469 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012470 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012471 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012472 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012473 app.adjType = "home";
12474 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012475
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012476 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12477 && app.activities.size() > 0) {
12478 // This was the previous process that showed UI to the user.
12479 // We want to try to keep it around more aggressively, to give
12480 // a good experience around switching between two apps.
12481 adj = ProcessList.PREVIOUS_APP_ADJ;
12482 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12483 app.hidden = false;
12484 app.adjType = "previous";
12485 }
12486
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012487 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12488 + " reason=" + app.adjType);
12489
The Android Open Source Project4df24232009-03-05 14:34:35 -080012490 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012491 // there are applications dependent on our services or providers, but
12492 // this gives us a baseline and makes sure we don't get into an
12493 // infinite recursion.
12494 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012495 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012496
Christopher Tate6fa95972009-06-05 18:43:55 -070012497 if (mBackupTarget != null && app == mBackupTarget.app) {
12498 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012499 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012500 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012501 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012502 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012503 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012504 }
12505 }
12506
Dianne Hackborn7d608422011-08-07 16:24:18 -070012507 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012508 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012509 final long now = SystemClock.uptimeMillis();
12510 // This process is more important if the top activity is
12511 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012512 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012513 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012514 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012515 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012516 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012517 // If this process has shown some UI, let it immediately
12518 // go to the LRU list because it may be pretty heavy with
12519 // UI stuff. We'll tag it with a label just to help
12520 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012521 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012522 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012523 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012524 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012525 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012526 // This service has seen some activity within
12527 // recent memory, so we will keep its process ahead
12528 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012529 if (adj > ProcessList.SERVICE_ADJ) {
12530 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012531 app.adjType = "started-services";
12532 app.hidden = false;
12533 }
12534 }
12535 // If we have let the service slide into the background
12536 // state, still have some text describing what it is doing
12537 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012538 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012539 app.adjType = "started-bg-services";
12540 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012541 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012542 // Don't kill this process because it is doing work; it
12543 // has said it is doing work.
12544 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012545 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012546 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012547 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012548 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012549 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012550 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012551 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012552 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012553 // XXX should compute this based on the max of
12554 // all connected clients.
12555 ConnectionRecord cr = clist.get(i);
12556 if (cr.binding.client == app) {
12557 // Binding to ourself is not interesting.
12558 continue;
12559 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012560 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012561 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012562 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012563 int myHiddenAdj = hiddenAdj;
12564 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012565 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012566 myHiddenAdj = client.hiddenAdj;
12567 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012568 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012569 }
12570 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012571 int myEmptyAdj = emptyAdj;
12572 if (myEmptyAdj > client.emptyAdj) {
12573 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12574 myEmptyAdj = client.emptyAdj;
12575 } else {
12576 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12577 }
12578 }
12579 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12580 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012581 String adjType = null;
12582 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12583 // Not doing bind OOM management, so treat
12584 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012585 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012586 // If this process has shown some UI, let it immediately
12587 // go to the LRU list because it may be pretty heavy with
12588 // UI stuff. We'll tag it with a label just to help
12589 // debug and understand what is going on.
12590 if (adj > clientAdj) {
12591 adjType = "bound-bg-ui-services";
12592 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012593 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012594 clientAdj = adj;
12595 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012596 if (now >= (s.lastActivity
12597 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012598 // This service has not seen activity within
12599 // recent memory, so allow it to drop to the
12600 // LRU list if there is no other reason to keep
12601 // it around. We'll also tag it with a label just
12602 // to help debug and undertand what is going on.
12603 if (adj > clientAdj) {
12604 adjType = "bound-bg-services";
12605 }
12606 clientAdj = adj;
12607 }
12608 }
12609 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012610 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012611 // If this process has recently shown UI, and
12612 // the process that is binding to it is less
12613 // important than being visible, then we don't
12614 // care about the binding as much as we care
12615 // about letting this process get into the LRU
12616 // list to be killed and restarted if needed for
12617 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012618 if (app.hasShownUi && app != mHomeProcess
12619 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012620 adjType = "bound-bg-ui-services";
12621 } else {
12622 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12623 |Context.BIND_IMPORTANT)) != 0) {
12624 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012625 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12626 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12627 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12628 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12629 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012630 adj = clientAdj;
12631 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012632 app.pendingUiClean = true;
12633 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12634 adj = ProcessList.VISIBLE_APP_ADJ;
12635 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012636 }
12637 if (!client.hidden) {
12638 app.hidden = false;
12639 }
12640 if (client.keeping) {
12641 app.keeping = true;
12642 }
12643 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012644 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012645 }
12646 if (adjType != null) {
12647 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012648 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12649 .REASON_SERVICE_IN_USE;
12650 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012651 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012652 app.adjTarget = s.name;
12653 }
12654 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12655 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12656 schedGroup = Process.THREAD_GROUP_DEFAULT;
12657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012658 }
12659 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012660 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12661 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012662 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012663 (a.visible || a.state == ActivityState.RESUMED
12664 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012665 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012666 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12667 schedGroup = Process.THREAD_GROUP_DEFAULT;
12668 }
12669 app.hidden = false;
12670 app.adjType = "service";
12671 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12672 .REASON_SERVICE_IN_USE;
12673 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012674 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012675 app.adjTarget = s.name;
12676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012678 }
12679 }
12680 }
12681 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012682
Dianne Hackborn287952c2010-09-22 22:34:31 -070012683 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012684 // would like to avoid killing it unless it would prevent the current
12685 // application from running. By default we put the process in
12686 // with the rest of the background processes; as we scan through
12687 // its services we may bump it up from there.
12688 if (adj > hiddenAdj) {
12689 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012690 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012691 app.adjType = "bg-services";
12692 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012693 }
12694
Dianne Hackborn7d608422011-08-07 16:24:18 -070012695 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012696 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012697 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012698 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012699 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012700 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012701 for (int i = cpr.connections.size()-1;
12702 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12703 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12704 i--) {
12705 ContentProviderConnection conn = cpr.connections.get(i);
12706 ProcessRecord client = conn.client;
12707 if (client == app) {
12708 // Being our own client is not interesting.
12709 continue;
12710 }
12711 int myHiddenAdj = hiddenAdj;
12712 if (myHiddenAdj > client.hiddenAdj) {
12713 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12714 myHiddenAdj = client.hiddenAdj;
12715 } else {
12716 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012717 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012718 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012719 int myEmptyAdj = emptyAdj;
12720 if (myEmptyAdj > client.emptyAdj) {
12721 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12722 myEmptyAdj = client.emptyAdj;
12723 } else {
12724 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12725 }
12726 }
12727 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12728 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012729 if (adj > clientAdj) {
12730 if (app.hasShownUi && app != mHomeProcess
12731 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12732 app.adjType = "bg-ui-provider";
12733 } else {
12734 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12735 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12736 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012737 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012738 if (!client.hidden) {
12739 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012740 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012741 if (client.keeping) {
12742 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012743 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012744 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12745 .REASON_PROVIDER_IN_USE;
12746 app.adjSource = client;
12747 app.adjSourceOom = clientAdj;
12748 app.adjTarget = cpr.name;
12749 }
12750 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12751 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012752 }
12753 }
12754 // If the provider has external (non-framework) process
12755 // dependencies, ensure that its adjustment is at least
12756 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012757 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012758 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12759 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012760 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012761 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012762 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012763 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012764 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012765 }
12766 }
12767 }
12768 }
12769
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012770 if (adj == ProcessList.SERVICE_ADJ) {
12771 if (doingAll) {
12772 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12773 mNewNumServiceProcs++;
12774 }
12775 if (app.serviceb) {
12776 adj = ProcessList.SERVICE_B_ADJ;
12777 }
12778 } else {
12779 app.serviceb = false;
12780 }
12781
12782 app.nonStoppingAdj = adj;
12783
12784 if (hasStoppingActivities) {
12785 // Only upgrade adjustment.
12786 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12787 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12788 app.adjType = "stopping";
12789 }
12790 }
12791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012792 app.curRawAdj = adj;
12793
Joe Onorato8a9b2202010-02-26 18:56:32 -080012794 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012795 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12796 if (adj > app.maxAdj) {
12797 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012798 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012799 schedGroup = Process.THREAD_GROUP_DEFAULT;
12800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012801 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012802 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012803 app.keeping = true;
12804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012805
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012806 if (app.hasAboveClient) {
12807 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12808 // then we need to drop its adjustment to be lower than the service's
12809 // in order to honor the request. We want to drop it by one adjustment
12810 // level... but there is special meaning applied to various levels so
12811 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012812 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012813 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012814 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12815 adj = ProcessList.VISIBLE_APP_ADJ;
12816 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12817 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12818 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12819 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012820 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012821 adj++;
12822 }
12823 }
12824
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012825 int importance = app.memImportance;
12826 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12827 app.curAdj = adj;
12828 app.curSchedGroup = schedGroup;
12829 if (!interesting) {
12830 // For this reporting, if there is not something explicitly
12831 // interesting in this process then we will push it to the
12832 // background importance.
12833 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12834 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12835 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12836 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12837 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12838 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12839 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12840 } else if (adj >= ProcessList.SERVICE_ADJ) {
12841 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12842 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12843 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12844 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12845 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
12846 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
12847 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
12848 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
12849 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
12850 } else {
12851 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
12852 }
12853 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012854
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012855 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
12856 if (foregroundActivities != app.foregroundActivities) {
12857 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
12858 }
12859 if (changes != 0) {
12860 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
12861 app.memImportance = importance;
12862 app.foregroundActivities = foregroundActivities;
12863 int i = mPendingProcessChanges.size()-1;
12864 ProcessChangeItem item = null;
12865 while (i >= 0) {
12866 item = mPendingProcessChanges.get(i);
12867 if (item.pid == app.pid) {
12868 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
12869 break;
12870 }
12871 i--;
12872 }
12873 if (i < 0) {
12874 // No existing item in pending changes; need a new one.
12875 final int NA = mAvailProcessChanges.size();
12876 if (NA > 0) {
12877 item = mAvailProcessChanges.remove(NA-1);
12878 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
12879 } else {
12880 item = new ProcessChangeItem();
12881 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
12882 }
12883 item.changes = 0;
12884 item.pid = app.pid;
12885 item.uid = app.info.uid;
12886 if (mPendingProcessChanges.size() == 0) {
12887 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
12888 "*** Enqueueing dispatch processes changed!");
12889 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
12890 }
12891 mPendingProcessChanges.add(item);
12892 }
12893 item.changes |= changes;
12894 item.importance = importance;
12895 item.foregroundActivities = foregroundActivities;
12896 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
12897 + Integer.toHexString(System.identityHashCode(item))
12898 + " " + app.toShortString() + ": changes=" + item.changes
12899 + " importance=" + item.importance
12900 + " foreground=" + item.foregroundActivities
12901 + " type=" + app.adjType + " source=" + app.adjSource
12902 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012903 }
12904
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012905 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012906 }
12907
12908 /**
12909 * Ask a given process to GC right now.
12910 */
12911 final void performAppGcLocked(ProcessRecord app) {
12912 try {
12913 app.lastRequestedGc = SystemClock.uptimeMillis();
12914 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012915 if (app.reportLowMemory) {
12916 app.reportLowMemory = false;
12917 app.thread.scheduleLowMemory();
12918 } else {
12919 app.thread.processInBackground();
12920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012921 }
12922 } catch (Exception e) {
12923 // whatever.
12924 }
12925 }
12926
12927 /**
12928 * Returns true if things are idle enough to perform GCs.
12929 */
Josh Bartel7f208742010-02-25 11:01:44 -060012930 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080012931 boolean processingBroadcasts = false;
12932 for (BroadcastQueue q : mBroadcastQueues) {
12933 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
12934 processingBroadcasts = true;
12935 }
12936 }
12937 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012938 && (mSleeping || (mMainStack.mResumedActivity != null &&
12939 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012940 }
12941
12942 /**
12943 * Perform GCs on all processes that are waiting for it, but only
12944 * if things are idle.
12945 */
12946 final void performAppGcsLocked() {
12947 final int N = mProcessesToGc.size();
12948 if (N <= 0) {
12949 return;
12950 }
Josh Bartel7f208742010-02-25 11:01:44 -060012951 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012952 while (mProcessesToGc.size() > 0) {
12953 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012954 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012955 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
12956 <= SystemClock.uptimeMillis()) {
12957 // To avoid spamming the system, we will GC processes one
12958 // at a time, waiting a few seconds between each.
12959 performAppGcLocked(proc);
12960 scheduleAppGcsLocked();
12961 return;
12962 } else {
12963 // It hasn't been long enough since we last GCed this
12964 // process... put it in the list to wait for its time.
12965 addProcessToGcListLocked(proc);
12966 break;
12967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012968 }
12969 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012970
12971 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012972 }
12973 }
12974
12975 /**
12976 * If all looks good, perform GCs on all processes waiting for them.
12977 */
12978 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060012979 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012980 performAppGcsLocked();
12981 return;
12982 }
12983 // Still not idle, wait some more.
12984 scheduleAppGcsLocked();
12985 }
12986
12987 /**
12988 * Schedule the execution of all pending app GCs.
12989 */
12990 final void scheduleAppGcsLocked() {
12991 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012992
12993 if (mProcessesToGc.size() > 0) {
12994 // Schedule a GC for the time to the next process.
12995 ProcessRecord proc = mProcessesToGc.get(0);
12996 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
12997
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012998 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012999 long now = SystemClock.uptimeMillis();
13000 if (when < (now+GC_TIMEOUT)) {
13001 when = now + GC_TIMEOUT;
13002 }
13003 mHandler.sendMessageAtTime(msg, when);
13004 }
13005 }
13006
13007 /**
13008 * Add a process to the array of processes waiting to be GCed. Keeps the
13009 * list in sorted order by the last GC time. The process can't already be
13010 * on the list.
13011 */
13012 final void addProcessToGcListLocked(ProcessRecord proc) {
13013 boolean added = false;
13014 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13015 if (mProcessesToGc.get(i).lastRequestedGc <
13016 proc.lastRequestedGc) {
13017 added = true;
13018 mProcessesToGc.add(i+1, proc);
13019 break;
13020 }
13021 }
13022 if (!added) {
13023 mProcessesToGc.add(0, proc);
13024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013025 }
13026
13027 /**
13028 * Set up to ask a process to GC itself. This will either do it
13029 * immediately, or put it on the list of processes to gc the next
13030 * time things are idle.
13031 */
13032 final void scheduleAppGcLocked(ProcessRecord app) {
13033 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013034 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013035 return;
13036 }
13037 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013038 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013039 scheduleAppGcsLocked();
13040 }
13041 }
13042
Dianne Hackborn287952c2010-09-22 22:34:31 -070013043 final void checkExcessivePowerUsageLocked(boolean doKills) {
13044 updateCpuStatsNow();
13045
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013046 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013047 boolean doWakeKills = doKills;
13048 boolean doCpuKills = doKills;
13049 if (mLastPowerCheckRealtime == 0) {
13050 doWakeKills = false;
13051 }
13052 if (mLastPowerCheckUptime == 0) {
13053 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013054 }
13055 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013056 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013057 }
13058 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013059 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13060 final long curUptime = SystemClock.uptimeMillis();
13061 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13062 mLastPowerCheckRealtime = curRealtime;
13063 mLastPowerCheckUptime = curUptime;
13064 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13065 doWakeKills = false;
13066 }
13067 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13068 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013069 }
13070 int i = mLruProcesses.size();
13071 while (i > 0) {
13072 i--;
13073 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013074 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013075 long wtime;
13076 synchronized (stats) {
13077 wtime = stats.getProcessWakeTime(app.info.uid,
13078 app.pid, curRealtime);
13079 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013080 long wtimeUsed = wtime - app.lastWakeTime;
13081 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13082 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013083 StringBuilder sb = new StringBuilder(128);
13084 sb.append("Wake for ");
13085 app.toShortString(sb);
13086 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013087 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013088 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013089 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013090 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013091 sb.append((wtimeUsed*100)/realtimeSince);
13092 sb.append("%)");
13093 Slog.i(TAG, sb.toString());
13094 sb.setLength(0);
13095 sb.append("CPU for ");
13096 app.toShortString(sb);
13097 sb.append(": over ");
13098 TimeUtils.formatDuration(uptimeSince, sb);
13099 sb.append(" used ");
13100 TimeUtils.formatDuration(cputimeUsed, sb);
13101 sb.append(" (");
13102 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013103 sb.append("%)");
13104 Slog.i(TAG, sb.toString());
13105 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013106 // If a process has held a wake lock for more
13107 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013108 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013109 if (doWakeKills && realtimeSince > 0
13110 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13111 synchronized (stats) {
13112 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13113 realtimeSince, wtimeUsed);
13114 }
13115 Slog.w(TAG, "Excessive wake lock in " + app.processName
13116 + " (pid " + app.pid + "): held " + wtimeUsed
13117 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013118 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13119 app.processName, app.setAdj, "excessive wake lock");
13120 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013121 } else if (doCpuKills && uptimeSince > 0
13122 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13123 synchronized (stats) {
13124 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13125 uptimeSince, cputimeUsed);
13126 }
13127 Slog.w(TAG, "Excessive CPU in " + app.processName
13128 + " (pid " + app.pid + "): used " + cputimeUsed
13129 + " during " + uptimeSince);
13130 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13131 app.processName, app.setAdj, "excessive cpu");
13132 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013133 } else {
13134 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013135 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013136 }
13137 }
13138 }
13139 }
13140
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013141 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
13142 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013143 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013144 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013145
13146 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013147 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013148 }
13149
Dianne Hackborn287952c2010-09-22 22:34:31 -070013150 final boolean wasKeeping = app.keeping;
13151
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013152 boolean success = true;
13153
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013154 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013155
Jeff Brown10e89712011-07-08 18:52:57 -070013156 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013157 if (wasKeeping && !app.keeping) {
13158 // This app is no longer something we want to keep. Note
13159 // its current wake lock time to later know to kill it if
13160 // it is not behaving well.
13161 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13162 synchronized (stats) {
13163 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13164 app.pid, SystemClock.elapsedRealtime());
13165 }
13166 app.lastCpuTime = app.curCpuTime;
13167 }
13168
13169 app.setRawAdj = app.curRawAdj;
13170 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013171
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013172 if (app.curAdj != app.setAdj) {
13173 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013174 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013175 TAG, "Set " + app.pid + " " + app.processName +
13176 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013177 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013178 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013179 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013180 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013181 }
13182 }
13183 if (app.setSchedGroup != app.curSchedGroup) {
13184 app.setSchedGroup = app.curSchedGroup;
13185 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13186 "Setting process group of " + app.processName
13187 + " to " + app.curSchedGroup);
13188 if (app.waitingToKill != null &&
13189 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13190 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13191 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13192 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013193 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013194 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013195 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013196 } else {
13197 if (true) {
13198 long oldId = Binder.clearCallingIdentity();
13199 try {
13200 Process.setProcessGroup(app.pid, app.curSchedGroup);
13201 } catch (Exception e) {
13202 Slog.w(TAG, "Failed setting process group of " + app.pid
13203 + " to " + app.curSchedGroup);
13204 e.printStackTrace();
13205 } finally {
13206 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013207 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013208 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013209 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013210 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013211 app.thread.setSchedulingGroup(app.curSchedGroup);
13212 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013213 }
13214 }
13215 }
13216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013217 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013218 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013219 }
13220
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013221 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013222 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013223 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013224 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013225 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013226 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013227 }
13228 }
13229 return resumedActivity;
13230 }
13231
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013232 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013233 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013234 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13235 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013236 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13237 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013238
13239 mAdjSeq++;
13240
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013241 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
13242 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013243 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13244 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013245 if (nowHidden != wasHidden) {
13246 // Changed to/from hidden state, so apps after it in the LRU
13247 // list may also be changed.
13248 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013249 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013250 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013251 }
13252
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013253 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013254 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013255 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13256
13257 if (false) {
13258 RuntimeException e = new RuntimeException();
13259 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013260 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013261 }
13262
13263 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013264 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013265
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013266 // Let's determine how many processes we have running vs.
13267 // how many slots we have for background processes; we may want
13268 // to put multiple processes in a slot of there are enough of
13269 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013270 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13271 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
13272 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
13273 if (emptyFactor < 1) emptyFactor = 1;
13274 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13275 if (hiddenFactor < 1) hiddenFactor = 1;
13276 int stepHidden = 0;
13277 int stepEmpty = 0;
13278 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
13279 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013280 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013281 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013282 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013283
13284 mNumNonHiddenProcs = 0;
13285 mNumHiddenProcs = 0;
13286
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013287 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013288 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013289 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013290 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013291 int nextHiddenAdj = curHiddenAdj+1;
13292 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13293 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013294 while (i > 0) {
13295 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013296 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013297 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013298 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013299 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013300 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13301 // This process was assigned as a hidden process... step the
13302 // hidden level.
13303 mNumHiddenProcs++;
13304 if (curHiddenAdj != nextHiddenAdj) {
13305 stepHidden++;
13306 if (stepHidden >= hiddenFactor) {
13307 stepHidden = 0;
13308 curHiddenAdj = nextHiddenAdj;
13309 nextHiddenAdj += 2;
13310 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13311 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13312 }
13313 }
13314 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013315 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013316 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013317 Slog.i(TAG, "No longer want " + app.processName
13318 + " (pid " + app.pid + "): hidden #" + numHidden);
13319 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13320 app.processName, app.setAdj, "too many background");
13321 app.killedBackground = true;
13322 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013323 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013324 } else {
13325 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13326 // This process was assigned as an empty process... step the
13327 // empty level.
13328 if (curEmptyAdj != nextEmptyAdj) {
13329 stepEmpty++;
13330 if (stepEmpty >= emptyFactor) {
13331 stepEmpty = 0;
13332 curEmptyAdj = nextEmptyAdj;
13333 nextEmptyAdj += 2;
13334 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13335 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13336 }
13337 }
13338 }
13339 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13340 mNumNonHiddenProcs++;
13341 }
13342 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13343 numEmpty++;
13344 if (numEmpty > emptyProcessLimit) {
13345 Slog.i(TAG, "No longer want " + app.processName
13346 + " (pid " + app.pid + "): empty #" + numEmpty);
13347 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13348 app.processName, app.setAdj, "too many background");
13349 app.killedBackground = true;
13350 Process.killProcessQuiet(app.pid);
13351 }
13352 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013353 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013354 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013355 // If this is an isolated process, and there are no
13356 // services running in it, then the process is no longer
13357 // needed. We agressively kill these because we can by
13358 // definition not re-use the same process again, and it is
13359 // good to avoid having whatever code was running in them
13360 // left sitting around after no longer needed.
13361 Slog.i(TAG, "Isolated process " + app.processName
13362 + " (pid " + app.pid + ") no longer needed");
13363 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13364 app.processName, app.setAdj, "isolated not needed");
13365 app.killedBackground = true;
13366 Process.killProcessQuiet(app.pid);
13367 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013368 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13369 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13370 && !app.killedBackground) {
13371 numTrimming++;
13372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013373 }
13374 }
13375
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013376 mNumServiceProcs = mNewNumServiceProcs;
13377
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013378 // Now determine the memory trimming level of background processes.
13379 // Unfortunately we need to start at the back of the list to do this
13380 // properly. We only do this if the number of background apps we
13381 // are managing to keep around is less than half the maximum we desire;
13382 // if we are keeping a good number around, we'll let them use whatever
13383 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013384 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13385 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13386 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013387 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013388 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013389 int minFactor = 2;
13390 if (mHomeProcess != null) minFactor++;
13391 if (mPreviousProcess != null) minFactor++;
13392 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013393 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013394 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013395 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013396 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013397 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013398 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13399 } else {
13400 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13401 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013402 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013403 for (i=0; i<N; i++) {
13404 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013405 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13406 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013407 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013408 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13409 try {
13410 app.thread.scheduleTrimMemory(curLevel);
13411 } catch (RemoteException e) {
13412 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013413 if (false) {
13414 // For now we won't do this; our memory trimming seems
13415 // to be good enough at this point that destroying
13416 // activities causes more harm than good.
13417 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13418 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013419 // Need to do this on its own message because the stack may not
13420 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013421 // For these apps we will also finish their activities
13422 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013423 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013424 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013425 }
13426 }
13427 app.trimMemoryLevel = curLevel;
13428 step++;
13429 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013430 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013431 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013432 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13433 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013434 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013435 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13436 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013437 break;
13438 }
13439 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013440 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013441 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013442 && app.thread != null) {
13443 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013444 app.thread.scheduleTrimMemory(
13445 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013446 } catch (RemoteException e) {
13447 }
13448 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013449 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013450 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013451 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013452 && app.pendingUiClean) {
13453 // If this application is now in the background and it
13454 // had done UI, then give it the special trim level to
13455 // have it free UI resources.
13456 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13457 if (app.trimMemoryLevel < level && app.thread != null) {
13458 try {
13459 app.thread.scheduleTrimMemory(level);
13460 } catch (RemoteException e) {
13461 }
13462 }
13463 app.pendingUiClean = false;
13464 }
13465 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013466 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013467 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013468 } catch (RemoteException e) {
13469 }
13470 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013471 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013472 }
13473 }
13474 } else {
13475 final int N = mLruProcesses.size();
13476 for (i=0; i<N; i++) {
13477 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013478 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013479 && app.pendingUiClean) {
13480 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13481 && app.thread != null) {
13482 try {
13483 app.thread.scheduleTrimMemory(
13484 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13485 } catch (RemoteException e) {
13486 }
13487 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013488 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013489 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013490 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013491 }
13492 }
13493
13494 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013495 // Need to do this on its own message because the stack may not
13496 // be in a consistent state at this point.
13497 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013499 }
13500
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013501 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013502 synchronized (this) {
13503 int i;
13504
13505 // First remove any unused application processes whose package
13506 // has been removed.
13507 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13508 final ProcessRecord app = mRemovedProcesses.get(i);
13509 if (app.activities.size() == 0
13510 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013511 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013512 TAG, "Exiting empty application process "
13513 + app.processName + " ("
13514 + (app.thread != null ? app.thread.asBinder() : null)
13515 + ")\n");
13516 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013517 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13518 app.processName, app.setAdj, "empty");
13519 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013520 } else {
13521 try {
13522 app.thread.scheduleExit();
13523 } catch (Exception e) {
13524 // Ignore exceptions.
13525 }
13526 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013527 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013528 mRemovedProcesses.remove(i);
13529
13530 if (app.persistent) {
13531 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013532 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013533 }
13534 }
13535 }
13536 }
13537
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013538 // Now update the oom adj for all processes.
13539 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013540 }
13541 }
13542
13543 /** This method sends the specified signal to each of the persistent apps */
13544 public void signalPersistentProcesses(int sig) throws RemoteException {
13545 if (sig != Process.SIGNAL_USR1) {
13546 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13547 }
13548
13549 synchronized (this) {
13550 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13551 != PackageManager.PERMISSION_GRANTED) {
13552 throw new SecurityException("Requires permission "
13553 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13554 }
13555
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013556 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13557 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013558 if (r.thread != null && r.persistent) {
13559 Process.sendSignal(r.pid, sig);
13560 }
13561 }
13562 }
13563 }
13564
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013565 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13566 if (proc == null || proc == mProfileProc) {
13567 proc = mProfileProc;
13568 path = mProfileFile;
13569 profileType = mProfileType;
13570 clearProfilerLocked();
13571 }
13572 if (proc == null) {
13573 return;
13574 }
13575 try {
13576 proc.thread.profilerControl(false, path, null, profileType);
13577 } catch (RemoteException e) {
13578 throw new IllegalStateException("Process disappeared");
13579 }
13580 }
13581
13582 private void clearProfilerLocked() {
13583 if (mProfileFd != null) {
13584 try {
13585 mProfileFd.close();
13586 } catch (IOException e) {
13587 }
13588 }
13589 mProfileApp = null;
13590 mProfileProc = null;
13591 mProfileFile = null;
13592 mProfileType = 0;
13593 mAutoStopProfiler = false;
13594 }
13595
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013596 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013597 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013598
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013599 try {
13600 synchronized (this) {
13601 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13602 // its own permission.
13603 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13604 != PackageManager.PERMISSION_GRANTED) {
13605 throw new SecurityException("Requires permission "
13606 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013607 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013608
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013609 if (start && fd == null) {
13610 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013611 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013612
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013613 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013614 if (process != null) {
13615 try {
13616 int pid = Integer.parseInt(process);
13617 synchronized (mPidsSelfLocked) {
13618 proc = mPidsSelfLocked.get(pid);
13619 }
13620 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013621 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013622
13623 if (proc == null) {
13624 HashMap<String, SparseArray<ProcessRecord>> all
13625 = mProcessNames.getMap();
13626 SparseArray<ProcessRecord> procs = all.get(process);
13627 if (procs != null && procs.size() > 0) {
13628 proc = procs.valueAt(0);
13629 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013630 }
13631 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013632
13633 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013634 throw new IllegalArgumentException("Unknown process: " + process);
13635 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013636
13637 if (start) {
13638 stopProfilerLocked(null, null, 0);
13639 setProfileApp(proc.info, proc.processName, path, fd, false);
13640 mProfileProc = proc;
13641 mProfileType = profileType;
13642 try {
13643 fd = fd.dup();
13644 } catch (IOException e) {
13645 fd = null;
13646 }
13647 proc.thread.profilerControl(start, path, fd, profileType);
13648 fd = null;
13649 mProfileFd = null;
13650 } else {
13651 stopProfilerLocked(proc, path, profileType);
13652 if (fd != null) {
13653 try {
13654 fd.close();
13655 } catch (IOException e) {
13656 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013657 }
13658 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013659
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013660 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013661 }
13662 } catch (RemoteException e) {
13663 throw new IllegalStateException("Process disappeared");
13664 } finally {
13665 if (fd != null) {
13666 try {
13667 fd.close();
13668 } catch (IOException e) {
13669 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013670 }
13671 }
13672 }
Andy McFadden824c5102010-07-09 16:26:57 -070013673
13674 public boolean dumpHeap(String process, boolean managed,
13675 String path, ParcelFileDescriptor fd) throws RemoteException {
13676
13677 try {
13678 synchronized (this) {
13679 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13680 // its own permission (same as profileControl).
13681 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13682 != PackageManager.PERMISSION_GRANTED) {
13683 throw new SecurityException("Requires permission "
13684 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13685 }
13686
13687 if (fd == null) {
13688 throw new IllegalArgumentException("null fd");
13689 }
13690
13691 ProcessRecord proc = null;
13692 try {
13693 int pid = Integer.parseInt(process);
13694 synchronized (mPidsSelfLocked) {
13695 proc = mPidsSelfLocked.get(pid);
13696 }
13697 } catch (NumberFormatException e) {
13698 }
13699
13700 if (proc == null) {
13701 HashMap<String, SparseArray<ProcessRecord>> all
13702 = mProcessNames.getMap();
13703 SparseArray<ProcessRecord> procs = all.get(process);
13704 if (procs != null && procs.size() > 0) {
13705 proc = procs.valueAt(0);
13706 }
13707 }
13708
13709 if (proc == null || proc.thread == null) {
13710 throw new IllegalArgumentException("Unknown process: " + process);
13711 }
13712
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013713 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13714 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013715 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13716 throw new SecurityException("Process not debuggable: " + proc);
13717 }
13718 }
13719
13720 proc.thread.dumpHeap(managed, path, fd);
13721 fd = null;
13722 return true;
13723 }
13724 } catch (RemoteException e) {
13725 throw new IllegalStateException("Process disappeared");
13726 } finally {
13727 if (fd != null) {
13728 try {
13729 fd.close();
13730 } catch (IOException e) {
13731 }
13732 }
13733 }
13734 }
13735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013736 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13737 public void monitor() {
13738 synchronized (this) { }
13739 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013740
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013741 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013742 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13743 ProcessRecord processRecord = mLruProcesses.get(i);
13744 try {
13745 if (processRecord.thread != null) {
13746 processRecord.thread.setCoreSettings(settings);
13747 }
13748 } catch (RemoteException re) {
13749 /* ignore */
13750 }
13751 }
13752 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013753
13754 // Multi-user methods
13755
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013756 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070013757 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013758 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13759 != PackageManager.PERMISSION_GRANTED) {
13760 String msg = "Permission Denial: switchUser() from pid="
13761 + Binder.getCallingPid()
13762 + ", uid=" + Binder.getCallingUid()
13763 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13764 Slog.w(TAG, msg);
13765 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013766 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013767 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013768 if (mCurrentUserId == userId) {
13769 return true;
13770 }
13771
13772 // If the user we are switching to is not currently started, then
13773 // we need to start it now.
13774 if (mStartedUsers.get(userId) == null) {
13775 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Amith Yamasani742a6712011-05-04 14:49:28 -070013776 }
13777
13778 mCurrentUserId = userId;
13779 boolean haveActivities = mMainStack.switchUser(userId);
13780 if (!haveActivities) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013781 startHomeActivityLocked(userId, mStartedUsers.get(userId));
Amith Yamasani742a6712011-05-04 14:49:28 -070013782 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013783 }
Amith Yamasani13593602012-03-22 16:16:17 -070013784
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013785 long ident = Binder.clearCallingIdentity();
13786 try {
13787 // Inform of user switch
13788 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
13789 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070013790 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
13791 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013792 } finally {
13793 Binder.restoreCallingIdentity(ident);
13794 }
Amith Yamasani13593602012-03-22 16:16:17 -070013795
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013796 return true;
13797 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013798
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013799 void finishUserSwitch(UserStartedState uss) {
13800 synchronized (this) {
13801 if (uss.mState == UserStartedState.STATE_BOOTING
13802 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
13803 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070013804 final int userId = uss.mHandle.getIdentifier();
13805 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
13806 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
13807 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013808 null, null, 0, null, null,
13809 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070013810 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013811 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013812 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013813 }
13814
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013815 @Override
13816 public int stopUser(final int userId, final IStopUserCallback callback) {
13817 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13818 != PackageManager.PERMISSION_GRANTED) {
13819 String msg = "Permission Denial: switchUser() from pid="
13820 + Binder.getCallingPid()
13821 + ", uid=" + Binder.getCallingUid()
13822 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13823 Slog.w(TAG, msg);
13824 throw new SecurityException(msg);
13825 }
13826 if (userId <= 0) {
13827 throw new IllegalArgumentException("Can't stop primary user " + userId);
13828 }
Amith Yamasani13593602012-03-22 16:16:17 -070013829 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013830 if (mCurrentUserId == userId) {
13831 return ActivityManager.USER_OP_IS_CURRENT;
13832 }
13833
13834 final UserStartedState uss = mStartedUsers.get(userId);
13835 if (uss == null) {
13836 // User is not started, nothing to do... but we do need to
13837 // callback if requested.
13838 if (callback != null) {
13839 mHandler.post(new Runnable() {
13840 @Override
13841 public void run() {
13842 try {
13843 callback.userStopped(userId);
13844 } catch (RemoteException e) {
13845 }
13846 }
13847 });
13848 }
13849 return ActivityManager.USER_OP_SUCCESS;
13850 }
13851
13852 if (callback != null) {
13853 uss.mStopCallbacks.add(callback);
13854 }
13855
13856 if (uss.mState != UserStartedState.STATE_STOPPING) {
13857 uss.mState = UserStartedState.STATE_STOPPING;
13858
13859 long ident = Binder.clearCallingIdentity();
13860 try {
13861 // Inform of user switch
13862 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
13863 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
13864 @Override
13865 public void performReceive(Intent intent, int resultCode, String data,
Dianne Hackborn20e80982012-08-31 19:00:44 -070013866 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013867 finishUserStop(uss);
13868 }
13869 };
13870 broadcastIntentLocked(null, null, intent,
13871 null, resultReceiver, 0, null, null, null,
13872 true, false, MY_PID, Process.SYSTEM_UID, userId);
13873 } finally {
13874 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070013875 }
13876 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013877 }
Amith Yamasani13593602012-03-22 16:16:17 -070013878
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013879 return ActivityManager.USER_OP_SUCCESS;
13880 }
13881
13882 void finishUserStop(UserStartedState uss) {
13883 final int userId = uss.mHandle.getIdentifier();
13884 boolean stopped;
13885 ArrayList<IStopUserCallback> callbacks;
13886 synchronized (this) {
13887 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
13888 if (uss.mState != UserStartedState.STATE_STOPPING
13889 || mStartedUsers.get(userId) != uss) {
13890 stopped = false;
13891 } else {
13892 stopped = true;
13893 // User can no longer run.
13894 mStartedUsers.remove(userId);
13895
13896 // Clean up all state and processes associated with the user.
13897 // Kill all the processes for the user.
13898 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070013899 }
13900 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013901
13902 for (int i=0; i<callbacks.size(); i++) {
13903 try {
13904 if (stopped) callbacks.get(i).userStopped(userId);
13905 else callbacks.get(i).userStopAborted(userId);
13906 } catch (RemoteException e) {
13907 }
13908 }
13909 }
13910
13911 @Override
13912 public UserInfo getCurrentUser() {
13913 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13914 != PackageManager.PERMISSION_GRANTED) {
13915 String msg = "Permission Denial: getCurrentUser() from pid="
13916 + Binder.getCallingPid()
13917 + ", uid=" + Binder.getCallingUid()
13918 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13919 Slog.w(TAG, msg);
13920 throw new SecurityException(msg);
13921 }
13922 synchronized (this) {
13923 return getUserManager().getUserInfo(mCurrentUserId);
13924 }
Amith Yamasani13593602012-03-22 16:16:17 -070013925 }
13926
Amith Yamasani742a6712011-05-04 14:49:28 -070013927 private boolean userExists(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -070013928 UserInfo user = getUserManager().getUserInfo(userId);
13929 return user != null;
13930 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013931
Amith Yamasani258848d2012-08-10 17:06:33 -070013932 UserManager getUserManager() {
13933 if (mUserManager == null) {
13934 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
13935 }
13936 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070013937 }
13938
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013939 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013940 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013941
13942 throw new SecurityException("Caller uid=" + uid
13943 + " is not privileged to communicate with user=" + userId);
13944 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013945
13946 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013947 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070013948 }
13949
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013950 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080013951 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070013952 ApplicationInfo newInfo = new ApplicationInfo(info);
13953 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070013954 newInfo.dataDir = USER_DATA_DIR + userId + "/"
13955 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070013956 return newInfo;
13957 }
13958
13959 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070013960 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013961 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070013962 return aInfo;
13963 }
13964
13965 ActivityInfo info = new ActivityInfo(aInfo);
13966 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
13967 return info;
13968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013969}