blob: 76a4f15aef1938897c2241d9931548e31c46ccc4 [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;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700124import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125import android.view.Gravity;
126import android.view.LayoutInflater;
127import android.view.View;
128import android.view.WindowManager;
129import android.view.WindowManagerPolicy;
130
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700131import java.io.BufferedInputStream;
132import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700133import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700134import java.io.DataInputStream;
135import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136import java.io.File;
137import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700138import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700140import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200141import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800142import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700144import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.lang.ref.WeakReference;
146import java.util.ArrayList;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700147import java.util.Collections;
148import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149import java.util.HashMap;
150import java.util.HashSet;
151import java.util.Iterator;
152import java.util.List;
153import java.util.Locale;
154import java.util.Map;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700155import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700156import java.util.concurrent.atomic.AtomicBoolean;
157import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700159public final class ActivityManagerService extends ActivityManagerNative
160 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700161 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700163 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400165 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 static final boolean DEBUG_SWITCH = localLOGV || false;
167 static final boolean DEBUG_TASKS = localLOGV || false;
168 static final boolean DEBUG_PAUSE = localLOGV || false;
169 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
170 static final boolean DEBUG_TRANSITION = localLOGV || false;
171 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800172 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700173 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700175 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final boolean DEBUG_VISBILITY = localLOGV || false;
177 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700178 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700179 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800180 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700182 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700183 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700184 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700185 static final boolean DEBUG_POWER = localLOGV || false;
186 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700187 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 static final boolean VALIDATE_TOKENS = false;
189 static final boolean SHOW_ACTIVITY_START_TIME = true;
190
191 // Control over CPU and battery monitoring.
192 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
193 static final boolean MONITOR_CPU_USAGE = true;
194 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
195 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
196 static final boolean MONITOR_THREAD_CPU_USAGE = false;
197
Dianne Hackborn1655be42009-05-08 14:29:01 -0700198 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700199 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700200
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800201 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700203 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 // Maximum number of recent tasks that we can remember.
206 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700207
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700208 // Amount of time after a call to stopAppSwitches() during which we will
209 // prevent further untrusted switches from happening.
210 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
212 // How long we wait for a launched process to attach to the activity manager
213 // before we decide it's never going to come up for real.
214 static final int PROC_START_TIMEOUT = 10*1000;
215
Jeff Brown3f9dd282011-07-08 20:02:19 -0700216 // How long we wait for a launched process to attach to the activity manager
217 // before we decide it's never going to come up for real, when the process was
218 // started with a wrapper for instrumentation (such as Valgrind) because it
219 // could take much longer than usual.
220 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 // How long to wait after going idle before forcing apps to GC.
223 static final int GC_TIMEOUT = 5*1000;
224
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700225 // The minimum amount of time between successive GC requests for a process.
226 static final int GC_MIN_INTERVAL = 60*1000;
227
Dianne Hackborn287952c2010-09-22 22:34:31 -0700228 // The rate at which we check for apps using excessive power -- 15 mins.
229 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
230
231 // The minimum sample duration we will allow before deciding we have
232 // enough data on wake locks to start killing things.
233 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
234
235 // The minimum sample duration we will allow before deciding we have
236 // enough data on CPU usage to start killing things.
237 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800240 static final int BROADCAST_FG_TIMEOUT = 10*1000;
241 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 // How long we wait until we timeout on key dispatching.
244 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 // How long we wait until we timeout on key dispatching during instrumentation.
247 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
248
Dan Egnor42471dd2010-01-07 17:25:22 -0800249 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250
251 static final String[] EMPTY_STRING_ARRAY = new String[0];
252
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700253 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700254
255 private final boolean mHeadless;
256
Joe Onorato54a4a412011-11-02 20:50:08 -0700257 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
258 // default actuion automatically. Important for devices without direct input
259 // devices.
260 private boolean mShowDialogs = true;
261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700263 * Description of a request to start a new activity, which has been held
264 * due to app switches being disabled.
265 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700266 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700267 ActivityRecord r;
268 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700269 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700270 }
271
272 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
273 = new ArrayList<PendingActivityLaunch>();
274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800276 BroadcastQueue mFgBroadcastQueue;
277 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800278 // Convenient for easy iteration over the queues. Foreground is first
279 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800280 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800281
282 BroadcastQueue broadcastQueueForIntent(Intent intent) {
283 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
284 if (DEBUG_BACKGROUND_BROADCAST) {
285 Slog.i(TAG, "Broadcast intent " + intent + " on "
286 + (isFg ? "foreground" : "background")
287 + " queue");
288 }
289 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
290 }
291
292 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
293 for (BroadcastQueue queue : mBroadcastQueues) {
294 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
295 if (r != null) {
296 return r;
297 }
298 }
299 return null;
300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301
302 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 * Activity we have told the window manager to have key focus.
304 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700305 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700306 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 * List of intents that were used to start the most recent tasks.
308 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700309 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310
311 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700312 * Process management.
313 */
314 final ProcessList mProcessList = new ProcessList();
315
316 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 * All of the applications we currently have running organized by name.
318 * The keys are strings of the application package name (as
319 * returned by the package manager), and the keys are ApplicationRecord
320 * objects.
321 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700322 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323
324 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800325 * The currently running isolated processes.
326 */
327 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
328
329 /**
330 * Counter for assigning isolated process uids, to avoid frequently reusing the
331 * same ones.
332 */
333 int mNextIsolatedProcessUid = 0;
334
335 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700336 * The currently running heavy-weight process, if any.
337 */
338 ProcessRecord mHeavyWeightProcess = null;
339
340 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 * The last time that various processes have crashed.
342 */
343 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
344
345 /**
346 * Set of applications that we consider to be bad, and will reject
347 * incoming broadcasts from (which the user has no control over).
348 * Processes are added to this set when they have crashed twice within
349 * a minimum amount of time; they are removed from it when they are
350 * later restarted (hopefully due to some user action). The value is the
351 * time it was added to the list.
352 */
353 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
354
355 /**
356 * All of the processes we currently have running organized by pid.
357 * The keys are the pid running the application.
358 *
359 * <p>NOTE: This object is protected by its own lock, NOT the global
360 * activity manager lock!
361 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700362 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800363
364 /**
365 * All of the processes that have been forced to be foreground. The key
366 * is the pid of the caller who requested it (we hold a death
367 * link on it).
368 */
369 abstract class ForegroundToken implements IBinder.DeathRecipient {
370 int pid;
371 IBinder token;
372 }
373 final SparseArray<ForegroundToken> mForegroundProcesses
374 = new SparseArray<ForegroundToken>();
375
376 /**
377 * List of records for processes that someone had tried to start before the
378 * system was ready. We don't start them at that point, but ensure they
379 * are started by the time booting is complete.
380 */
381 final ArrayList<ProcessRecord> mProcessesOnHold
382 = new ArrayList<ProcessRecord>();
383
384 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800385 * List of persistent applications that are in the process
386 * of being started.
387 */
388 final ArrayList<ProcessRecord> mPersistentStartingProcesses
389 = new ArrayList<ProcessRecord>();
390
391 /**
392 * Processes that are being forcibly torn down.
393 */
394 final ArrayList<ProcessRecord> mRemovedProcesses
395 = new ArrayList<ProcessRecord>();
396
397 /**
398 * List of running applications, sorted by recent usage.
399 * The first entry in the list is the least recently used.
400 * It contains ApplicationRecord objects. This list does NOT include
401 * any persistent application records (since we never want to exit them).
402 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800403 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800404 = new ArrayList<ProcessRecord>();
405
406 /**
407 * List of processes that should gc as soon as things are idle.
408 */
409 final ArrayList<ProcessRecord> mProcessesToGc
410 = new ArrayList<ProcessRecord>();
411
412 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800413 * This is the process holding what we currently consider to be
414 * the "home" activity.
415 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700416 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800417
418 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700419 * This is the process holding the activity the user last visited that
420 * is in a different process from the one they are currently in.
421 */
422 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800423
424 /**
425 * The time at which the previous process was last visible.
426 */
427 long mPreviousProcessVisibleTime;
428
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700429 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700430 * Which uses have been started, so are allowed to run code.
431 */
432 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
433
434 /**
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -0700435 * LRU list of history of current users. Most recently current is at the end.
436 */
437 final ArrayList<Integer> mUserLru = new ArrayList<Integer>();
438
439 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400440 * Packages that the user has asked to have run in screen size
441 * compatibility mode instead of filling the screen.
442 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700443 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400444
445 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800446 * Set of PendingResultRecord objects that are currently active.
447 */
448 final HashSet mPendingResultRecords = new HashSet();
449
450 /**
451 * Set of IntentSenderRecord objects that are currently active.
452 */
453 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
454 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
455
456 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800457 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700458 * already logged DropBox entries for. Guarded by itself. If
459 * something (rogue user app) forces this over
460 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
461 */
462 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
463 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
464
465 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700466 * Strict Mode background batched logging state.
467 *
468 * The string buffer is guarded by itself, and its lock is also
469 * used to determine if another batched write is already
470 * in-flight.
471 */
472 private final StringBuilder mStrictModeBuffer = new StringBuilder();
473
474 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475 * Keeps track of all IIntentReceivers that have been registered for
476 * broadcasts. Hash keys are the receiver IBinder, hash value is
477 * a ReceiverList.
478 */
479 final HashMap mRegisteredReceivers = new HashMap();
480
481 /**
482 * Resolver for broadcast intents to registered receivers.
483 * Holds BroadcastFilter (subclass of IntentFilter).
484 */
485 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
486 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
487 @Override
488 protected boolean allowFilterResult(
489 BroadcastFilter filter, List<BroadcastFilter> dest) {
490 IBinder target = filter.receiverList.receiver.asBinder();
491 for (int i=dest.size()-1; i>=0; i--) {
492 if (dest.get(i).receiverList.receiver.asBinder() == target) {
493 return false;
494 }
495 }
496 return true;
497 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700498
499 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700500 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
Dianne Hackborn20e80982012-08-31 19:00:44 -0700501 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL
502 || userId == filter.owningUserId) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700503 return super.newResult(filter, match, userId);
504 }
505 return null;
506 }
507
508 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700509 protected BroadcastFilter[] newArray(int size) {
510 return new BroadcastFilter[size];
511 }
512
513 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700514 protected String packageForFilter(BroadcastFilter filter) {
515 return filter.packageName;
516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 };
518
519 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700520 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700522 * that action (which should usually be one). The SparseArray is keyed
523 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
524 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700526 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
527 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700529 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530
531 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700532 * Backup/restore process management
533 */
534 String mBackupAppName = null;
535 BackupRecord mBackupTarget = null;
536
537 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 * List of PendingThumbnailsRecord objects of clients who are still
539 * waiting to receive all of the thumbnails for a task.
540 */
541 final ArrayList mPendingThumbnails = new ArrayList();
542
543 /**
544 * List of HistoryRecord objects that have been finished and must
545 * still report back to a pending thumbnail receiver.
546 */
547 final ArrayList mCancelledThumbnails = new ArrayList();
548
Amith Yamasani742a6712011-05-04 14:49:28 -0700549 final ProviderMap mProviderMap = new ProviderMap();
550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551 /**
552 * List of content providers who have clients waiting for them. The
553 * application is currently being launched and the provider will be
554 * removed from this list once it is published.
555 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700556 final ArrayList<ContentProviderRecord> mLaunchingProviders
557 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558
559 /**
560 * Global set of specific Uri permissions that have been granted.
561 */
562 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
563 = new SparseArray<HashMap<Uri, UriPermission>>();
564
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800565 CoreSettingsObserver mCoreSettingsObserver;
566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800567 /**
568 * Thread-local storage used to carry caller permissions over through
569 * indirect content-provider access.
570 * @see #ActivityManagerService.openContentUri()
571 */
572 private class Identity {
573 public int pid;
574 public int uid;
575
576 Identity(int _pid, int _uid) {
577 pid = _pid;
578 uid = _uid;
579 }
580 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
583
584 /**
585 * All information we have collected about the runtime performance of
586 * any user id that can impact battery performance.
587 */
588 final BatteryStatsService mBatteryStatsService;
589
590 /**
591 * information about component usage
592 */
593 final UsageStatsService mUsageStatsService;
594
595 /**
596 * Current configuration information. HistoryRecord objects are given
597 * a reference to this object to indicate which configuration they are
598 * currently running in, so this object must be kept immutable.
599 */
600 Configuration mConfiguration = new Configuration();
601
602 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800603 * Current sequencing integer of the configuration, for skipping old
604 * configurations.
605 */
606 int mConfigurationSeq = 0;
607
608 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700609 * Hardware-reported OpenGLES version.
610 */
611 final int GL_ES_VERSION;
612
613 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800614 * List of initialization arguments to pass to all processes when binding applications to them.
615 * For example, references to the commonly used services.
616 */
617 HashMap<String, IBinder> mAppBindArgs;
618
619 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700620 * Temporary to avoid allocations. Protected by main lock.
621 */
622 final StringBuilder mStringBuilder = new StringBuilder(256);
623
624 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 * Used to control how we initialize the service.
626 */
627 boolean mStartRunning = false;
628 ComponentName mTopComponent;
629 String mTopAction;
630 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700631 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 boolean mSystemReady = false;
633 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700634 boolean mWaitingUpdate = false;
635 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700636 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700637 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638
639 Context mContext;
640
641 int mFactoryTest;
642
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700643 boolean mCheckedForSetup;
644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700646 * The time at which we will allow normal application switches again,
647 * after a call to {@link #stopAppSwitches()}.
648 */
649 long mAppSwitchesAllowedTime;
650
651 /**
652 * This is set to true after the first switch after mAppSwitchesAllowedTime
653 * is set; any switches after that will clear the time.
654 */
655 boolean mDidAppSwitch;
656
657 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700658 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700659 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700660 long mLastPowerCheckRealtime;
661
662 /**
663 * Last time (in uptime) at which we checked for power usage.
664 */
665 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700666
667 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800668 * Set while we are wanting to sleep, to prevent any
669 * activities from being started/resumed.
670 */
671 boolean mSleeping = false;
672
673 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700674 * State of external calls telling us if the device is asleep.
675 */
676 boolean mWentToSleep = false;
677
678 /**
679 * State of external call telling us if the lock screen is shown.
680 */
681 boolean mLockScreenShown = false;
682
683 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700684 * Set if we are shutting down the system, similar to sleeping.
685 */
686 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800687
688 /**
689 * Task identifier that activities are currently being started
690 * in. Incremented each time a new task is created.
691 * todo: Replace this with a TokenSpace class that generates non-repeating
692 * integers that won't wrap.
693 */
694 int mCurTask = 1;
695
696 /**
697 * Current sequence id for oom_adj computation traversal.
698 */
699 int mAdjSeq = 0;
700
701 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700702 * Current sequence id for process LRU updating.
703 */
704 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800705
706 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700707 * Keep track of the non-hidden/empty process we last found, to help
708 * determine how to distribute hidden/empty processes next time.
709 */
710 int mNumNonHiddenProcs = 0;
711
712 /**
713 * Keep track of the number of hidden procs, to balance oom adj
714 * distribution between those and empty procs.
715 */
716 int mNumHiddenProcs = 0;
717
718 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700719 * Keep track of the number of service processes we last found, to
720 * determine on the next iteration which should be B services.
721 */
722 int mNumServiceProcs = 0;
723 int mNewNumServiceProcs = 0;
724
725 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 * System monitoring: number of processes that died since the last
727 * N procs were started.
728 */
729 int[] mProcDeaths = new int[20];
730
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700731 /**
732 * This is set if we had to do a delayed dexopt of an app before launching
733 * it, to increasing the ANR timeouts in that case.
734 */
735 boolean mDidDexOpt;
736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800737 String mDebugApp = null;
738 boolean mWaitForDebugger = false;
739 boolean mDebugTransient = false;
740 String mOrigDebugApp = null;
741 boolean mOrigWaitForDebugger = false;
742 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700743 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700744 String mProfileApp = null;
745 ProcessRecord mProfileProc = null;
746 String mProfileFile;
747 ParcelFileDescriptor mProfileFd;
748 int mProfileType = 0;
749 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800750 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700752 static class ProcessChangeItem {
753 static final int CHANGE_ACTIVITIES = 1<<0;
754 static final int CHANGE_IMPORTANCE= 1<<1;
755 int changes;
756 int uid;
757 int pid;
758 int importance;
759 boolean foregroundActivities;
760 }
761
Jeff Sharkeya4620792011-05-20 15:29:23 -0700762 final RemoteCallbackList<IProcessObserver> mProcessObservers
763 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700764 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
765
766 final ArrayList<ProcessChangeItem> mPendingProcessChanges
767 = new ArrayList<ProcessChangeItem>();
768 final ArrayList<ProcessChangeItem> mAvailProcessChanges
769 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771 /**
772 * Callback of last caller to {@link #requestPss}.
773 */
774 Runnable mRequestPssCallback;
775
776 /**
777 * Remaining processes for which we are waiting results from the last
778 * call to {@link #requestPss}.
779 */
780 final ArrayList<ProcessRecord> mRequestPssList
781 = new ArrayList<ProcessRecord>();
782
783 /**
784 * Runtime statistics collection thread. This object's lock is used to
785 * protect all related state.
786 */
787 final Thread mProcessStatsThread;
788
789 /**
790 * Used to collect process stats when showing not responding dialog.
791 * Protected by mProcessStatsThread.
792 */
793 final ProcessStats mProcessStats = new ProcessStats(
794 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700795 final AtomicLong mLastCpuTime = new AtomicLong(0);
796 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 long mLastWriteTime = 0;
799
800 /**
801 * Set to true after the system has finished booting.
802 */
803 boolean mBooted = false;
804
Dianne Hackborn7d608422011-08-07 16:24:18 -0700805 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700806 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807
808 WindowManagerService mWindowManager;
809
810 static ActivityManagerService mSelf;
811 static ActivityThread mSystemThread;
812
Amith Yamasani258848d2012-08-10 17:06:33 -0700813 private int mCurrentUserId;
Amith Yamasani258848d2012-08-10 17:06:33 -0700814 private UserManager mUserManager;
815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 private final class AppDeathRecipient implements IBinder.DeathRecipient {
817 final ProcessRecord mApp;
818 final int mPid;
819 final IApplicationThread mAppThread;
820
821 AppDeathRecipient(ProcessRecord app, int pid,
822 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800823 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 TAG, "New death recipient " + this
825 + " for thread " + thread.asBinder());
826 mApp = app;
827 mPid = pid;
828 mAppThread = thread;
829 }
830
831 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800832 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 TAG, "Death received in " + this
834 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 synchronized(ActivityManagerService.this) {
836 appDiedLocked(mApp, mPid, mAppThread);
837 }
838 }
839 }
840
841 static final int SHOW_ERROR_MSG = 1;
842 static final int SHOW_NOT_RESPONDING_MSG = 2;
843 static final int SHOW_FACTORY_ERROR_MSG = 3;
844 static final int UPDATE_CONFIGURATION_MSG = 4;
845 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
846 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 static final int SERVICE_TIMEOUT_MSG = 12;
848 static final int UPDATE_TIME_ZONE = 13;
849 static final int SHOW_UID_ERROR_MSG = 14;
850 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700852 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700853 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800854 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700855 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
856 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700857 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700858 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700859 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700860 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700861 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700862 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700863 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700864 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800866 static final int FIRST_ACTIVITY_STACK_MSG = 100;
867 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
868 static final int FIRST_COMPAT_MODE_MSG = 300;
869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700871 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700872 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873
874 final Handler mHandler = new Handler() {
875 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800876 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 //}
878
879 public void handleMessage(Message msg) {
880 switch (msg.what) {
881 case SHOW_ERROR_MSG: {
882 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 synchronized (ActivityManagerService.this) {
884 ProcessRecord proc = (ProcessRecord)data.get("app");
885 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800886 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800887 return;
888 }
889 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700890 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800891 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 d.show();
893 proc.crashDialog = d;
894 } else {
895 // The device is asleep, so just pretend that the user
896 // saw a crash dialog and hit "force quit".
897 res.set(0);
898 }
899 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700900
901 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 } break;
903 case SHOW_NOT_RESPONDING_MSG: {
904 synchronized (ActivityManagerService.this) {
905 HashMap data = (HashMap) msg.obj;
906 ProcessRecord proc = (ProcessRecord)data.get("app");
907 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800908 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800909 return;
910 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800911
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700912 Intent intent = new Intent("android.intent.action.ANR");
913 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800914 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
915 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700916 }
917 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800918 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700919 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800920
Justin Kohbc52ca22012-03-29 15:11:44 -0700921 if (mShowDialogs) {
922 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700923 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700924 d.show();
925 proc.anrDialog = d;
926 } else {
927 // Just kill the app if there is no dialog to be shown.
928 killAppAtUsersRequest(proc, null);
929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700931
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700932 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700934 case SHOW_STRICT_MODE_VIOLATION_MSG: {
935 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
936 synchronized (ActivityManagerService.this) {
937 ProcessRecord proc = (ProcessRecord) data.get("app");
938 if (proc == null) {
939 Slog.e(TAG, "App not found when showing strict mode dialog.");
940 break;
941 }
942 if (proc.crashDialog != null) {
943 Slog.e(TAG, "App already has strict mode dialog: " + proc);
944 return;
945 }
946 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700947 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700948 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
949 d.show();
950 proc.crashDialog = d;
951 } else {
952 // The device is asleep, so just pretend that the user
953 // saw a crash dialog and hit "force quit".
954 res.set(0);
955 }
956 }
957 ensureBootCompleted();
958 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 case SHOW_FACTORY_ERROR_MSG: {
960 Dialog d = new FactoryErrorDialog(
961 mContext, msg.getData().getCharSequence("msg"));
962 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700963 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 } break;
965 case UPDATE_CONFIGURATION_MSG: {
966 final ContentResolver resolver = mContext.getContentResolver();
967 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
968 } break;
969 case GC_BACKGROUND_PROCESSES_MSG: {
970 synchronized (ActivityManagerService.this) {
971 performAppGcsIfAppropriateLocked();
972 }
973 } break;
974 case WAIT_FOR_DEBUGGER_MSG: {
975 synchronized (ActivityManagerService.this) {
976 ProcessRecord app = (ProcessRecord)msg.obj;
977 if (msg.arg1 != 0) {
978 if (!app.waitedForDebugger) {
979 Dialog d = new AppWaitingForDebuggerDialog(
980 ActivityManagerService.this,
981 mContext, app);
982 app.waitDialog = d;
983 app.waitedForDebugger = true;
984 d.show();
985 }
986 } else {
987 if (app.waitDialog != null) {
988 app.waitDialog.dismiss();
989 app.waitDialog = null;
990 }
991 }
992 }
993 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700995 if (mDidDexOpt) {
996 mDidDexOpt = false;
997 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
998 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700999 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001000 return;
1001 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001002 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 } break;
1004 case UPDATE_TIME_ZONE: {
1005 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001006 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1007 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 if (r.thread != null) {
1009 try {
1010 r.thread.updateTimeZone();
1011 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001012 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 }
1014 }
1015 }
1016 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001017 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001018 case CLEAR_DNS_CACHE: {
1019 synchronized (ActivityManagerService.this) {
1020 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1021 ProcessRecord r = mLruProcesses.get(i);
1022 if (r.thread != null) {
1023 try {
1024 r.thread.clearDnsCache();
1025 } catch (RemoteException ex) {
1026 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1027 }
1028 }
1029 }
1030 }
1031 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001032 case UPDATE_HTTP_PROXY: {
1033 ProxyProperties proxy = (ProxyProperties)msg.obj;
1034 String host = "";
1035 String port = "";
1036 String exclList = "";
1037 if (proxy != null) {
1038 host = proxy.getHost();
1039 port = Integer.toString(proxy.getPort());
1040 exclList = proxy.getExclusionList();
1041 }
1042 synchronized (ActivityManagerService.this) {
1043 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1044 ProcessRecord r = mLruProcesses.get(i);
1045 if (r.thread != null) {
1046 try {
1047 r.thread.setHttpProxy(host, port, exclList);
1048 } catch (RemoteException ex) {
1049 Slog.w(TAG, "Failed to update http proxy for: " +
1050 r.info.processName);
1051 }
1052 }
1053 }
1054 }
1055 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001057 String title = "System UIDs Inconsistent";
1058 String text = "UIDs on the system are inconsistent, you need to wipe your"
1059 + " data partition or your device will be unstable.";
1060 Log.e(TAG, title + ": " + text);
1061 if (mShowDialogs) {
1062 // XXX This is a temporary dialog, no need to localize.
1063 AlertDialog d = new BaseErrorDialog(mContext);
1064 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1065 d.setCancelable(false);
1066 d.setTitle(title);
1067 d.setMessage(text);
1068 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1069 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1070 mUidAlert = d;
1071 d.show();
1072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 } break;
1074 case IM_FEELING_LUCKY_MSG: {
1075 if (mUidAlert != null) {
1076 mUidAlert.dismiss();
1077 mUidAlert = null;
1078 }
1079 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001081 if (mDidDexOpt) {
1082 mDidDexOpt = false;
1083 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1084 nmsg.obj = msg.obj;
1085 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1086 return;
1087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 ProcessRecord app = (ProcessRecord)msg.obj;
1089 synchronized (ActivityManagerService.this) {
1090 processStartTimedOutLocked(app);
1091 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001092 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001093 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1094 synchronized (ActivityManagerService.this) {
1095 doPendingActivityLaunchesLocked(true);
1096 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001097 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001098 case KILL_APPLICATION_MSG: {
1099 synchronized (ActivityManagerService.this) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001100 int appid = msg.arg1;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001101 boolean restart = (msg.arg2 == 1);
1102 String pkg = (String) msg.obj;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001103 forceStopPackageLocked(pkg, appid, restart, false, true, false,
1104 UserHandle.USER_ALL);
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001105 }
1106 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001107 case FINALIZE_PENDING_INTENT_MSG: {
1108 ((PendingIntentRecord)msg.obj).completeFinalize();
1109 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001110 case POST_HEAVY_NOTIFICATION_MSG: {
1111 INotificationManager inm = NotificationManager.getService();
1112 if (inm == null) {
1113 return;
1114 }
1115
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001116 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001117 ProcessRecord process = root.app;
1118 if (process == null) {
1119 return;
1120 }
1121
1122 try {
1123 Context context = mContext.createPackageContext(process.info.packageName, 0);
1124 String text = mContext.getString(R.string.heavy_weight_notification,
1125 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1126 Notification notification = new Notification();
1127 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1128 notification.when = 0;
1129 notification.flags = Notification.FLAG_ONGOING_EVENT;
1130 notification.tickerText = text;
1131 notification.defaults = 0; // please be quiet
1132 notification.sound = null;
1133 notification.vibrate = null;
1134 notification.setLatestEventInfo(context, text,
1135 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001136 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1137 PendingIntent.FLAG_CANCEL_CURRENT, null,
1138 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001139
1140 try {
1141 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001142 inm.enqueueNotificationWithTag("android", null,
1143 R.string.heavy_weight_notification,
1144 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001145 } catch (RuntimeException e) {
1146 Slog.w(ActivityManagerService.TAG,
1147 "Error showing notification for heavy-weight app", e);
1148 } catch (RemoteException e) {
1149 }
1150 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001151 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001152 }
1153 } break;
1154 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1155 INotificationManager inm = NotificationManager.getService();
1156 if (inm == null) {
1157 return;
1158 }
1159 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001160 inm.cancelNotificationWithTag("android", null,
1161 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001162 } catch (RuntimeException e) {
1163 Slog.w(ActivityManagerService.TAG,
1164 "Error canceling notification for service", e);
1165 } catch (RemoteException e) {
1166 }
1167 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001168 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1169 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001170 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001171 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001172 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1173 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001174 }
1175 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001176 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1177 synchronized (ActivityManagerService.this) {
1178 ActivityRecord ar = (ActivityRecord)msg.obj;
1179 if (mCompatModeDialog != null) {
1180 if (mCompatModeDialog.mAppInfo.packageName.equals(
1181 ar.info.applicationInfo.packageName)) {
1182 return;
1183 }
1184 mCompatModeDialog.dismiss();
1185 mCompatModeDialog = null;
1186 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001187 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001188 if (mCompatModePackages.getPackageAskCompatModeLocked(
1189 ar.packageName)) {
1190 int mode = mCompatModePackages.computeCompatModeLocked(
1191 ar.info.applicationInfo);
1192 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1193 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1194 mCompatModeDialog = new CompatModeDialog(
1195 ActivityManagerService.this, mContext,
1196 ar.info.applicationInfo);
1197 mCompatModeDialog.show();
1198 }
1199 }
1200 }
1201 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001202 break;
1203 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001204 case DISPATCH_PROCESSES_CHANGED: {
1205 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001206 break;
1207 }
1208 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001209 final int pid = msg.arg1;
1210 final int uid = msg.arg2;
1211 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001212 break;
1213 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001214 case REPORT_MEM_USAGE: {
1215 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1216 if (!isDebuggable) {
1217 return;
1218 }
1219 synchronized (ActivityManagerService.this) {
1220 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001221 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1222 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001223 // avoid spamming.
1224 return;
1225 }
1226 mLastMemUsageReportTime = now;
1227 }
1228 Thread thread = new Thread() {
1229 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001230 StringBuilder dropBuilder = new StringBuilder(1024);
1231 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001232 StringWriter oomSw = new StringWriter();
1233 PrintWriter oomPw = new PrintWriter(oomSw);
1234 StringWriter catSw = new StringWriter();
1235 PrintWriter catPw = new PrintWriter(catSw);
1236 String[] emptyArgs = new String[] { };
1237 StringBuilder tag = new StringBuilder(128);
1238 StringBuilder stack = new StringBuilder(128);
1239 tag.append("Low on memory -- ");
1240 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1241 tag, stack);
1242 dropBuilder.append(stack);
1243 dropBuilder.append('\n');
1244 dropBuilder.append('\n');
1245 String oomString = oomSw.toString();
1246 dropBuilder.append(oomString);
1247 dropBuilder.append('\n');
1248 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001249 try {
1250 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1251 "procrank", });
1252 final InputStreamReader converter = new InputStreamReader(
1253 proc.getInputStream());
1254 BufferedReader in = new BufferedReader(converter);
1255 String line;
1256 while (true) {
1257 line = in.readLine();
1258 if (line == null) {
1259 break;
1260 }
1261 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001262 logBuilder.append(line);
1263 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001264 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001265 dropBuilder.append(line);
1266 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001267 }
1268 converter.close();
1269 } catch (IOException e) {
1270 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001271 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001272 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001273 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001274 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001275 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1276 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001277 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001278 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001279 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001280 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001281 addErrorToDropBox("lowmem", null, "system_server", null,
1282 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001283 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001284 synchronized (ActivityManagerService.this) {
1285 long now = SystemClock.uptimeMillis();
1286 if (mLastMemUsageReportTime < now) {
1287 mLastMemUsageReportTime = now;
1288 }
1289 }
1290 }
1291 };
1292 thread.start();
1293 break;
1294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 }
1296 }
1297 };
1298
1299 public static void setSystemProcess() {
1300 try {
1301 ActivityManagerService m = mSelf;
1302
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001303 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001305 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001306 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 if (MONITOR_CPU_USAGE) {
1308 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 ServiceManager.addService("permission", new PermissionController(m));
1311
1312 ApplicationInfo info =
1313 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001314 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001315 mSystemThread.installSystemApplicationInfo(info);
1316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 synchronized (mSelf) {
1318 ProcessRecord app = mSelf.newProcessRecordLocked(
1319 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001320 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001322 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001323 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001324 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 synchronized (mSelf.mPidsSelfLocked) {
1326 mSelf.mPidsSelfLocked.put(app.pid, app);
1327 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001328 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 }
1330 } catch (PackageManager.NameNotFoundException e) {
1331 throw new RuntimeException(
1332 "Unable to find android system package", e);
1333 }
1334 }
1335
1336 public void setWindowManager(WindowManagerService wm) {
1337 mWindowManager = wm;
1338 }
1339
1340 public static final Context main(int factoryTest) {
1341 AThread thr = new AThread();
1342 thr.start();
1343
1344 synchronized (thr) {
1345 while (thr.mService == null) {
1346 try {
1347 thr.wait();
1348 } catch (InterruptedException e) {
1349 }
1350 }
1351 }
1352
1353 ActivityManagerService m = thr.mService;
1354 mSelf = m;
1355 ActivityThread at = ActivityThread.systemMain();
1356 mSystemThread = at;
1357 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001358 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 m.mContext = context;
1360 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001361 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362
1363 m.mBatteryStatsService.publish(context);
1364 m.mUsageStatsService.publish(context);
1365
1366 synchronized (thr) {
1367 thr.mReady = true;
1368 thr.notifyAll();
1369 }
1370
1371 m.startRunning(null, null, null, null);
1372
1373 return context;
1374 }
1375
1376 public static ActivityManagerService self() {
1377 return mSelf;
1378 }
1379
1380 static class AThread extends Thread {
1381 ActivityManagerService mService;
1382 boolean mReady = false;
1383
1384 public AThread() {
1385 super("ActivityManager");
1386 }
1387
1388 public void run() {
1389 Looper.prepare();
1390
1391 android.os.Process.setThreadPriority(
1392 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001393 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394
1395 ActivityManagerService m = new ActivityManagerService();
1396
1397 synchronized (this) {
1398 mService = m;
1399 notifyAll();
1400 }
1401
1402 synchronized (this) {
1403 while (!mReady) {
1404 try {
1405 wait();
1406 } catch (InterruptedException e) {
1407 }
1408 }
1409 }
1410
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001411 // For debug builds, log event loop stalls to dropbox for analysis.
1412 if (StrictMode.conditionallyEnableDebugLogging()) {
1413 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1414 }
1415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 Looper.loop();
1417 }
1418 }
1419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 static class MemBinder extends Binder {
1421 ActivityManagerService mActivityManagerService;
1422 MemBinder(ActivityManagerService activityManagerService) {
1423 mActivityManagerService = activityManagerService;
1424 }
1425
1426 @Override
1427 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001428 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1429 != PackageManager.PERMISSION_GRANTED) {
1430 pw.println("Permission Denial: can't dump meminfo from from pid="
1431 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1432 + " without permission " + android.Manifest.permission.DUMP);
1433 return;
1434 }
1435
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001436 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001437 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439 }
1440
Chet Haase9c1e23b2011-03-24 10:51:31 -07001441 static class GraphicsBinder extends Binder {
1442 ActivityManagerService mActivityManagerService;
1443 GraphicsBinder(ActivityManagerService activityManagerService) {
1444 mActivityManagerService = activityManagerService;
1445 }
1446
1447 @Override
1448 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001449 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1450 != PackageManager.PERMISSION_GRANTED) {
1451 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1452 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1453 + " without permission " + android.Manifest.permission.DUMP);
1454 return;
1455 }
1456
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001457 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001458 }
1459 }
1460
Jeff Brown6754ba22011-12-14 20:20:01 -08001461 static class DbBinder extends Binder {
1462 ActivityManagerService mActivityManagerService;
1463 DbBinder(ActivityManagerService activityManagerService) {
1464 mActivityManagerService = activityManagerService;
1465 }
1466
1467 @Override
1468 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1469 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1470 != PackageManager.PERMISSION_GRANTED) {
1471 pw.println("Permission Denial: can't dump dbinfo from from pid="
1472 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1473 + " without permission " + android.Manifest.permission.DUMP);
1474 return;
1475 }
1476
1477 mActivityManagerService.dumpDbInfo(fd, pw, args);
1478 }
1479 }
1480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 static class CpuBinder extends Binder {
1482 ActivityManagerService mActivityManagerService;
1483 CpuBinder(ActivityManagerService activityManagerService) {
1484 mActivityManagerService = activityManagerService;
1485 }
1486
1487 @Override
1488 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001489 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1490 != PackageManager.PERMISSION_GRANTED) {
1491 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1492 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1493 + " without permission " + android.Manifest.permission.DUMP);
1494 return;
1495 }
1496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001498 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1499 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1500 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
1502 }
1503 }
1504
1505 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001506 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001507
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001508 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1509 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1510 mBroadcastQueues[0] = mFgBroadcastQueue;
1511 mBroadcastQueues[1] = mBgBroadcastQueue;
1512
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001513 mServices = new ActiveServices(this);
1514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 File dataDir = Environment.getDataDirectory();
1516 File systemDir = new File(dataDir, "system");
1517 systemDir.mkdirs();
1518 mBatteryStatsService = new BatteryStatsService(new File(
1519 systemDir, "batterystats.bin").toString());
1520 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001521 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001522 mOnBattery = DEBUG_POWER ? true
1523 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001524 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001526 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001527 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001528 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001530 // User 0 is the first and only user that runs at boot.
1531 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07001532 mUserLru.add(Integer.valueOf(0));
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001533
Jack Palevichb90d28c2009-07-22 15:35:24 -07001534 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1535 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1536
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001537 mConfiguration.setToDefaults();
Fabrice Di Meglio5f797992012-06-15 20:16:41 -07001538 mConfiguration.setLocale(Locale.getDefault());
1539
Dianne Hackborn813075a62011-11-14 17:45:19 -08001540 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 mProcessStats.init();
1542
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001543 mCompatModePackages = new CompatModePackages(this, systemDir);
1544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 // Add ourself to the Watchdog monitors.
1546 Watchdog.getInstance().addMonitor(this);
1547
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 mProcessStatsThread = new Thread("ProcessStats") {
1549 public void run() {
1550 while (true) {
1551 try {
1552 try {
1553 synchronized(this) {
1554 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001555 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001557 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 // + ", write delay=" + nextWriteDelay);
1559 if (nextWriteDelay < nextCpuDelay) {
1560 nextCpuDelay = nextWriteDelay;
1561 }
1562 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001563 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 this.wait(nextCpuDelay);
1565 }
1566 }
1567 } catch (InterruptedException e) {
1568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 updateCpuStatsNow();
1570 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001571 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001572 }
1573 }
1574 }
1575 };
1576 mProcessStatsThread.start();
1577 }
1578
1579 @Override
1580 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1581 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001582 if (code == SYSPROPS_TRANSACTION) {
1583 // We need to tell all apps about the system property change.
1584 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1585 synchronized(this) {
1586 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1587 final int NA = apps.size();
1588 for (int ia=0; ia<NA; ia++) {
1589 ProcessRecord app = apps.valueAt(ia);
1590 if (app.thread != null) {
1591 procs.add(app.thread.asBinder());
1592 }
1593 }
1594 }
1595 }
1596
1597 int N = procs.size();
1598 for (int i=0; i<N; i++) {
1599 Parcel data2 = Parcel.obtain();
1600 try {
1601 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1602 } catch (RemoteException e) {
1603 }
1604 data2.recycle();
1605 }
1606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 try {
1608 return super.onTransact(code, data, reply, flags);
1609 } catch (RuntimeException e) {
1610 // The activity manager only throws security exceptions, so let's
1611 // log all others.
1612 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001613 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 }
1615 throw e;
1616 }
1617 }
1618
1619 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001620 final long now = SystemClock.uptimeMillis();
1621 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1622 return;
1623 }
1624 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1625 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 mProcessStatsThread.notify();
1627 }
1628 }
1629 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 void updateCpuStatsNow() {
1632 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001633 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 final long now = SystemClock.uptimeMillis();
1635 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001638 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1639 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 haveNewCpuStats = true;
1641 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001642 //Slog.i(TAG, mProcessStats.printCurrentState());
1643 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 // + mProcessStats.getTotalCpuPercent() + "%");
1645
Joe Onorato8a9b2202010-02-26 18:56:32 -08001646 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 if ("true".equals(SystemProperties.get("events.cpu"))) {
1648 int user = mProcessStats.getLastUserTime();
1649 int system = mProcessStats.getLastSystemTime();
1650 int iowait = mProcessStats.getLastIoWaitTime();
1651 int irq = mProcessStats.getLastIrqTime();
1652 int softIrq = mProcessStats.getLastSoftIrqTime();
1653 int idle = mProcessStats.getLastIdleTime();
1654
1655 int total = user + system + iowait + irq + softIrq + idle;
1656 if (total == 0) total = 1;
1657
Doug Zongker2bec3d42009-12-04 12:52:44 -08001658 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001659 ((user+system+iowait+irq+softIrq) * 100) / total,
1660 (user * 100) / total,
1661 (system * 100) / total,
1662 (iowait * 100) / total,
1663 (irq * 100) / total,
1664 (softIrq * 100) / total);
1665 }
1666 }
1667
Amith Yamasanie43530a2009-08-21 13:11:37 -07001668 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001669 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001670 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 synchronized(mPidsSelfLocked) {
1672 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001673 if (mOnBattery) {
1674 int perc = bstats.startAddingCpuLocked();
1675 int totalUTime = 0;
1676 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001677 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001679 ProcessStats.Stats st = mProcessStats.getStats(i);
1680 if (!st.working) {
1681 continue;
1682 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001684 int otherUTime = (st.rel_utime*perc)/100;
1685 int otherSTime = (st.rel_stime*perc)/100;
1686 totalUTime += otherUTime;
1687 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 if (pr != null) {
1689 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001690 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1691 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001692 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001693 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001694 } else {
1695 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001696 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001697 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001698 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1699 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001700 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 }
1703 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001704 bstats.finishAddingCpuLocked(perc, totalUTime,
1705 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 }
1707 }
1708 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1711 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001712 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 }
1714 }
1715 }
1716 }
1717
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001718 @Override
1719 public void batteryNeedsCpuUpdate() {
1720 updateCpuStatsNow();
1721 }
1722
1723 @Override
1724 public void batteryPowerChanged(boolean onBattery) {
1725 // When plugging in, update the CPU stats first before changing
1726 // the plug state.
1727 updateCpuStatsNow();
1728 synchronized (this) {
1729 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001730 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001731 }
1732 }
1733 }
1734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 /**
1736 * Initialize the application bind args. These are passed to each
1737 * process when the bindApplication() IPC is sent to the process. They're
1738 * lazily setup to make sure the services are running when they're asked for.
1739 */
1740 private HashMap<String, IBinder> getCommonServicesLocked() {
1741 if (mAppBindArgs == null) {
1742 mAppBindArgs = new HashMap<String, IBinder>();
1743
1744 // Setup the application init args
1745 mAppBindArgs.put("package", ServiceManager.getService("package"));
1746 mAppBindArgs.put("window", ServiceManager.getService("window"));
1747 mAppBindArgs.put(Context.ALARM_SERVICE,
1748 ServiceManager.getService(Context.ALARM_SERVICE));
1749 }
1750 return mAppBindArgs;
1751 }
1752
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001753 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 if (mFocusedActivity != r) {
1755 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001756 if (r != null) {
1757 mWindowManager.setFocusedApp(r.appToken, true);
1758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001759 }
1760 }
1761
Dianne Hackborn906497c2010-05-10 15:57:38 -07001762 private final void updateLruProcessInternalLocked(ProcessRecord app,
1763 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001765 int lrui = mLruProcesses.indexOf(app);
1766 if (lrui >= 0) mLruProcesses.remove(lrui);
1767
1768 int i = mLruProcesses.size()-1;
1769 int skipTop = 0;
1770
Dianne Hackborn906497c2010-05-10 15:57:38 -07001771 app.lruSeq = mLruSeq;
1772
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001773 // compute the new weight for this process.
1774 if (updateActivityTime) {
1775 app.lastActivityTime = SystemClock.uptimeMillis();
1776 }
1777 if (app.activities.size() > 0) {
1778 // If this process has activities, we more strongly want to keep
1779 // it around.
1780 app.lruWeight = app.lastActivityTime;
1781 } else if (app.pubProviders.size() > 0) {
1782 // If this process contains content providers, we want to keep
1783 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001784 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001785 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001786 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001787 } else {
1788 // If this process doesn't have activities, we less strongly
1789 // want to keep it around, and generally want to avoid getting
1790 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001791 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001792 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001793 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001794 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001795
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001796 while (i >= 0) {
1797 ProcessRecord p = mLruProcesses.get(i);
1798 // If this app shouldn't be in front of the first N background
1799 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001800 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001801 skipTop--;
1802 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001803 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001804 mLruProcesses.add(i+1, app);
1805 break;
1806 }
1807 i--;
1808 }
1809 if (i < 0) {
1810 mLruProcesses.add(0, app);
1811 }
1812
Dianne Hackborn906497c2010-05-10 15:57:38 -07001813 // If the app is currently using a content provider or service,
1814 // bump those processes as well.
1815 if (app.connections.size() > 0) {
1816 for (ConnectionRecord cr : app.connections) {
1817 if (cr.binding != null && cr.binding.service != null
1818 && cr.binding.service.app != null
1819 && cr.binding.service.app.lruSeq != mLruSeq) {
Björn Davidsson90f9e312010-11-18 08:26:27 +01001820 updateLruProcessInternalLocked(cr.binding.service.app, false,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001821 updateActivityTime, i+1);
1822 }
1823 }
1824 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001825 for (int j=app.conProviders.size()-1; j>=0; j--) {
1826 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1827 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Jean-Baptiste Querub8c64052012-06-11 11:01:19 -07001828 updateLruProcessInternalLocked(cpr.proc, false,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001829 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001830 }
1831 }
1832
Joe Onorato8a9b2202010-02-26 18:56:32 -08001833 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 if (oomAdj) {
1835 updateOomAdjLocked();
1836 }
1837 }
1838
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001839 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001840 boolean oomAdj, boolean updateActivityTime) {
1841 mLruSeq++;
1842 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1843 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001844
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001845 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001847 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001848 // The system gets to run in any process. If there are multiple
1849 // processes with the same uid, just pick the first (this
1850 // should never happen).
1851 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1852 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001853 if (procs == null) return null;
1854 final int N = procs.size();
1855 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001856 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001857 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 }
1859 ProcessRecord proc = mProcessNames.get(processName, uid);
1860 return proc;
1861 }
1862
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001863 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001864 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001865 try {
1866 if (pm.performDexOpt(packageName)) {
1867 mDidDexOpt = true;
1868 }
1869 } catch (RemoteException e) {
1870 }
1871 }
1872
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001873 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 int transit = mWindowManager.getPendingAppTransition();
1875 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1876 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1877 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1878 }
1879
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001880 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001882 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1883 boolean isolated) {
1884 ProcessRecord app;
1885 if (!isolated) {
1886 app = getProcessRecordLocked(processName, info.uid);
1887 } else {
1888 // If this is an isolated process, it can't re-use an existing process.
1889 app = null;
1890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 // We don't have to do anything more if:
1892 // (1) There is an existing application record; and
1893 // (2) The caller doesn't think it is dead, OR there is no thread
1894 // object attached to it so we know it couldn't have crashed; and
1895 // (3) There is a pid assigned to it, so it is either starting or
1896 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001897 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 + " app=" + app + " knownToBeDead=" + knownToBeDead
1899 + " thread=" + (app != null ? app.thread : null)
1900 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001901 if (app != null && app.pid > 0) {
1902 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001903 // We already have the app running, or are waiting for it to
1904 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001905 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001906 // If this is a new package in the process, add the package to the list
1907 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001908 return app;
1909 } else {
1910 // An application record is attached to a previous process,
1911 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001912 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001913 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 String hostingNameStr = hostingName != null
1918 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001919
1920 if (!isolated) {
1921 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1922 // If we are in the background, then check to see if this process
1923 // is bad. If so, we will just silently fail.
1924 if (mBadProcesses.get(info.processName, info.uid) != null) {
1925 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1926 + "/" + info.processName);
1927 return null;
1928 }
1929 } else {
1930 // When the user is explicitly starting a process, then clear its
1931 // crash count so that we won't make it bad until they see at
1932 // least one crash dialog again, and make the process good again
1933 // if it had been bad.
1934 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001935 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001936 mProcessCrashTimes.remove(info.processName, info.uid);
1937 if (mBadProcesses.get(info.processName, info.uid) != null) {
1938 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1939 info.processName);
1940 mBadProcesses.remove(info.processName, info.uid);
1941 if (app != null) {
1942 app.bad = false;
1943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 }
1945 }
1946 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001949 app = newProcessRecordLocked(null, info, processName, isolated);
1950 if (app == null) {
1951 Slog.w(TAG, "Failed making new process record for "
1952 + processName + "/" + info.uid + " isolated=" + isolated);
1953 return null;
1954 }
1955 mProcessNames.put(processName, app.uid, app);
1956 if (isolated) {
1957 mIsolatedProcesses.put(app.uid, app);
1958 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 } else {
1960 // If this is a new package in the process, add the package to the list
1961 app.addPackage(info.packageName);
1962 }
1963
1964 // If the system is not ready yet, then hold off on starting this
1965 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001966 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001967 && !isAllowedWhileBooting(info)
1968 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 if (!mProcessesOnHold.contains(app)) {
1970 mProcessesOnHold.add(app);
1971 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001972 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 return app;
1974 }
1975
1976 startProcessLocked(app, hostingType, hostingNameStr);
1977 return (app.pid != 0) ? app : null;
1978 }
1979
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001980 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1981 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1982 }
1983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 private final void startProcessLocked(ProcessRecord app,
1985 String hostingType, String hostingNameStr) {
1986 if (app.pid > 0 && app.pid != MY_PID) {
1987 synchronized (mPidsSelfLocked) {
1988 mPidsSelfLocked.remove(app.pid);
1989 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1990 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001991 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 }
1993
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001994 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1995 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001996 mProcessesOnHold.remove(app);
1997
1998 updateCpuStats();
1999
2000 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
2001 mProcDeaths[0] = 0;
2002
2003 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002004 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002005
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002007 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002008 if (!app.isolated) {
2009 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002010 final PackageManager pm = mContext.getPackageManager();
2011 gids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002012
2013 if (Environment.isExternalStorageEmulated()) {
2014 if (pm.checkPermission(
2015 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2016 app.info.packageName) == PERMISSION_GRANTED) {
2017 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2018 } else {
2019 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2020 }
2021 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002022 } catch (PackageManager.NameNotFoundException e) {
2023 Slog.w(TAG, "Unable to retrieve gids", e);
2024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002025 }
2026 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2027 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2028 && mTopComponent != null
2029 && app.processName.equals(mTopComponent.getPackageName())) {
2030 uid = 0;
2031 }
2032 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2033 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2034 uid = 0;
2035 }
2036 }
2037 int debugFlags = 0;
2038 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2039 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002040 // Also turn on CheckJNI for debuggable apps. It's quite
2041 // awkward to turn on otherwise.
2042 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002044 // Run the app in safe mode if its manifest requests so or the
2045 // system is booted in safe mode.
2046 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2047 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002048 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2051 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2052 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002053 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2054 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002056 if ("1".equals(SystemProperties.get("debug.assert"))) {
2057 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2058 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002059
2060 // Start the process. It will either succeed and return a result containing
2061 // the PID of the new process, or else throw a RuntimeException.
2062 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002063 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002064 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2067 synchronized (bs) {
2068 if (bs.isOnBattery()) {
2069 app.batteryStats.incStartsLocked();
2070 }
2071 }
2072
Jeff Brown3f9dd282011-07-08 20:02:19 -07002073 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 app.processName, hostingType,
2075 hostingNameStr != null ? hostingNameStr : "");
2076
2077 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002078 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
2080
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002081 StringBuilder buf = mStringBuilder;
2082 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 buf.append("Start proc ");
2084 buf.append(app.processName);
2085 buf.append(" for ");
2086 buf.append(hostingType);
2087 if (hostingNameStr != null) {
2088 buf.append(" ");
2089 buf.append(hostingNameStr);
2090 }
2091 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002092 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 buf.append(" uid=");
2094 buf.append(uid);
2095 buf.append(" gids={");
2096 if (gids != null) {
2097 for (int gi=0; gi<gids.length; gi++) {
2098 if (gi != 0) buf.append(", ");
2099 buf.append(gids[gi]);
2100
2101 }
2102 }
2103 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002104 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002105 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002106 app.usingWrapper = startResult.usingWrapper;
2107 app.removed = false;
2108 synchronized (mPidsSelfLocked) {
2109 this.mPidsSelfLocked.put(startResult.pid, app);
2110 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2111 msg.obj = app;
2112 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2113 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 }
2115 } catch (RuntimeException e) {
2116 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002117 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002118 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002119 }
2120 }
2121
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002122 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 if (resumed) {
2124 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2125 } else {
2126 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2127 }
2128 }
2129
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002130 boolean startHomeActivityLocked(int userId, UserStartedState startingUser) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002131 if (mHeadless) {
2132 // Added because none of the other calls to ensureBootCompleted seem to fire
2133 // when running headless.
2134 ensureBootCompleted();
2135 return false;
2136 }
2137
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002138 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2139 && mTopAction == null) {
2140 // We are running in factory test mode, but unable to find
2141 // the factory test app, so just sit around displaying the
2142 // error message and don't try to start anything.
2143 return false;
2144 }
2145 Intent intent = new Intent(
2146 mTopAction,
2147 mTopData != null ? Uri.parse(mTopData) : null);
2148 intent.setComponent(mTopComponent);
2149 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2150 intent.addCategory(Intent.CATEGORY_HOME);
2151 }
2152 ActivityInfo aInfo =
2153 intent.resolveActivityInfo(mContext.getPackageManager(),
2154 STOCK_PM_FLAGS);
2155 if (aInfo != null) {
2156 intent.setComponent(new ComponentName(
2157 aInfo.applicationInfo.packageName, aInfo.name));
2158 // Don't do this if the home app is currently being
2159 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002160 aInfo = new ActivityInfo(aInfo);
2161 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002162 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2163 aInfo.applicationInfo.uid);
2164 if (app == null || app.instrumentationClass == null) {
2165 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002166 mMainStack.startActivityLocked(null, intent, null, aInfo,
2167 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002168 }
2169 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002170 if (startingUser != null) {
2171 mMainStack.addStartingUserLocked(startingUser);
2172 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002173
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002174 return true;
2175 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002176
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002177 /**
2178 * Starts the "new version setup screen" if appropriate.
2179 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002180 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002181 // Only do this once per boot.
2182 if (mCheckedForSetup) {
2183 return;
2184 }
2185
2186 // We will show this screen if the current one is a different
2187 // version than the last one shown, and we are not running in
2188 // low-level factory test mode.
2189 final ContentResolver resolver = mContext.getContentResolver();
2190 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2191 Settings.Secure.getInt(resolver,
2192 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2193 mCheckedForSetup = true;
2194
2195 // See if we should be showing the platform update setup UI.
2196 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2197 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2198 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2199
2200 // We don't allow third party apps to replace this.
2201 ResolveInfo ri = null;
2202 for (int i=0; ris != null && i<ris.size(); i++) {
2203 if ((ris.get(i).activityInfo.applicationInfo.flags
2204 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2205 ri = ris.get(i);
2206 break;
2207 }
2208 }
2209
2210 if (ri != null) {
2211 String vers = ri.activityInfo.metaData != null
2212 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2213 : null;
2214 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2215 vers = ri.activityInfo.applicationInfo.metaData.getString(
2216 Intent.METADATA_SETUP_VERSION);
2217 }
2218 String lastVers = Settings.Secure.getString(
2219 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2220 if (vers != null && !vers.equals(lastVers)) {
2221 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2222 intent.setComponent(new ComponentName(
2223 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002224 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2225 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002226 }
2227 }
2228 }
2229 }
2230
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002231 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002232 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002233 }
2234
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002235 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002236 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002237 throw new SecurityException("Isolated process not allowed to call " + caller);
2238 }
2239 }
2240
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002241 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002242 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002243 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002244 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2245 }
2246 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002247
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002248 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002249 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2250 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002251 synchronized (this) {
2252 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2253 }
2254 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002255
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002256 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002257 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002258 synchronized (this) {
2259 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2260 }
2261 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002262
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002263 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002264 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2265 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002266 synchronized (this) {
2267 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002268 }
2269 }
2270
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002271 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002272 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002273 synchronized (this) {
2274 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2275 }
2276 }
2277
2278 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002279 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2280 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002281 synchronized (this) {
2282 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2283 }
2284 }
2285
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002286 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002287 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002288 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002291 private void dispatchProcessesChanged() {
2292 int N;
2293 synchronized (this) {
2294 N = mPendingProcessChanges.size();
2295 if (mActiveProcessChanges.length < N) {
2296 mActiveProcessChanges = new ProcessChangeItem[N];
2297 }
2298 mPendingProcessChanges.toArray(mActiveProcessChanges);
2299 mAvailProcessChanges.addAll(mPendingProcessChanges);
2300 mPendingProcessChanges.clear();
2301 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2302 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002303 int i = mProcessObservers.beginBroadcast();
2304 while (i > 0) {
2305 i--;
2306 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2307 if (observer != null) {
2308 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002309 for (int j=0; j<N; j++) {
2310 ProcessChangeItem item = mActiveProcessChanges[j];
2311 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2312 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2313 + item.pid + " uid=" + item.uid + ": "
2314 + item.foregroundActivities);
2315 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2316 item.foregroundActivities);
2317 }
2318 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2319 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2320 + item.pid + " uid=" + item.uid + ": " + item.importance);
2321 observer.onImportanceChanged(item.pid, item.uid,
2322 item.importance);
2323 }
2324 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002325 } catch (RemoteException e) {
2326 }
2327 }
2328 }
2329 mProcessObservers.finishBroadcast();
2330 }
2331
2332 private void dispatchProcessDied(int pid, int uid) {
2333 int i = mProcessObservers.beginBroadcast();
2334 while (i > 0) {
2335 i--;
2336 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2337 if (observer != null) {
2338 try {
2339 observer.onProcessDied(pid, uid);
2340 } catch (RemoteException e) {
2341 }
2342 }
2343 }
2344 mProcessObservers.finishBroadcast();
2345 }
2346
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002347 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002348 final int N = mPendingActivityLaunches.size();
2349 if (N <= 0) {
2350 return;
2351 }
2352 for (int i=0; i<N; i++) {
2353 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002354 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002355 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002356 }
2357 mPendingActivityLaunches.clear();
2358 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002359
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002360 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002361 Intent intent, String resolvedType, IBinder resultTo,
2362 String resultWho, int requestCode, int startFlags,
2363 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002364 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002365 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002366 }
2367
2368 public final int startActivityAsUser(IApplicationThread caller,
2369 Intent intent, String resolvedType, IBinder resultTo,
2370 String resultWho, int requestCode, int startFlags,
2371 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002372 enforceNotIsolatedCaller("startActivity");
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002373 if (userId != UserHandle.getCallingUserId()) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002374 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2375 false, true, "startActivity", null);
Amith Yamasani82644082012-08-03 13:09:11 -07002376 } else {
2377 if (intent.getCategories() != null
2378 && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2379 // Requesting home, set the identity to the current user
2380 // HACK!
2381 userId = mCurrentUserId;
Amith Yamasani742a6712011-05-04 14:49:28 -07002382 }
2383 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002384 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002385 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2386 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002387 }
2388
2389 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002390 Intent intent, String resolvedType, IBinder resultTo,
2391 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002392 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002393 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002394 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2395 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002396 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002397 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002398 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002399 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002400 return res;
2401 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002402
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002403 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002404 Intent intent, String resolvedType, IBinder resultTo,
2405 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002406 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002407 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn41203752012-08-31 14:05:51 -07002408 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2409 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002410 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002411 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002412 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002413 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002414 }
2415
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002416 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002417 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002418 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002419 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002420 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002421 // Refuse possible leaked file descriptors
2422 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2423 throw new IllegalArgumentException("File descriptors passed in Intent");
2424 }
2425
2426 IIntentSender sender = intent.getTarget();
2427 if (!(sender instanceof PendingIntentRecord)) {
2428 throw new IllegalArgumentException("Bad PendingIntent object");
2429 }
2430
2431 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002432
2433 synchronized (this) {
2434 // If this is coming from the currently resumed activity, it is
2435 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002436 if (mMainStack.mResumedActivity != null
2437 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002438 Binder.getCallingUid()) {
2439 mAppSwitchesAllowedTime = 0;
2440 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002441 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002442 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2443 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002444 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002445 }
2446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002448 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 // Refuse possible leaked file descriptors
2450 if (intent != null && intent.hasFileDescriptors() == true) {
2451 throw new IllegalArgumentException("File descriptors passed in Intent");
2452 }
2453
2454 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002455 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2456 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002457 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 return false;
2459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 if (r.app == null || r.app.thread == null) {
2461 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002462 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 return false;
2464 }
2465 intent = new Intent(intent);
2466 // The caller is not allowed to change the data.
2467 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2468 // And we are resetting to find the next component...
2469 intent.setComponent(null);
2470
2471 ActivityInfo aInfo = null;
2472 try {
2473 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002474 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002476 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002477 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478
2479 // Look for the original activity in the list...
2480 final int N = resolves != null ? resolves.size() : 0;
2481 for (int i=0; i<N; i++) {
2482 ResolveInfo rInfo = resolves.get(i);
2483 if (rInfo.activityInfo.packageName.equals(r.packageName)
2484 && rInfo.activityInfo.name.equals(r.info.name)) {
2485 // We found the current one... the next matching is
2486 // after it.
2487 i++;
2488 if (i<N) {
2489 aInfo = resolves.get(i).activityInfo;
2490 }
2491 break;
2492 }
2493 }
2494 } catch (RemoteException e) {
2495 }
2496
2497 if (aInfo == null) {
2498 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002499 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 return false;
2501 }
2502
2503 intent.setComponent(new ComponentName(
2504 aInfo.applicationInfo.packageName, aInfo.name));
2505 intent.setFlags(intent.getFlags()&~(
2506 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2507 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2508 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2509 Intent.FLAG_ACTIVITY_NEW_TASK));
2510
2511 // Okay now we need to start the new activity, replacing the
2512 // currently running activity. This is a little tricky because
2513 // we want to start the new one as if the current one is finished,
2514 // but not finish the current one first so that there is no flicker.
2515 // And thus...
2516 final boolean wasFinishing = r.finishing;
2517 r.finishing = true;
2518
2519 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002520 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 final String resultWho = r.resultWho;
2522 final int requestCode = r.requestCode;
2523 r.resultTo = null;
2524 if (resultTo != null) {
2525 resultTo.removeResultsLocked(r, resultWho, requestCode);
2526 }
2527
2528 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002529 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002530 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2531 resultWho, requestCode, -1, r.launchedFromUid, 0,
2532 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 Binder.restoreCallingIdentity(origId);
2534
2535 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002536 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 return false;
2538 }
2539 return true;
2540 }
2541 }
2542
Dianne Hackborn41203752012-08-31 14:05:51 -07002543 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002545 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2546
2547 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2548 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549
Amith Yamasani742a6712011-05-04 14:49:28 -07002550 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002551 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002552 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002553 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002554 }
2555
2556 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002557 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002558 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002559 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002560 options, UserHandle.getCallingUserId());
Amith Yamasani742a6712011-05-04 14:49:28 -07002561 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002562 }
2563
Dianne Hackborn41203752012-08-31 14:05:51 -07002564 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002565 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002566 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002567
Dianne Hackborn41203752012-08-31 14:05:51 -07002568 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2569 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002570 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002571 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002572 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 }
2574
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002575 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002577 // Quick case: check if the top-most recent task is the same.
2578 if (N > 0 && mRecentTasks.get(0) == task) {
2579 return;
2580 }
2581 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 for (int i=0; i<N; i++) {
2583 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002584 if (task.userId == tr.userId
2585 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2586 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 mRecentTasks.remove(i);
2588 i--;
2589 N--;
2590 if (task.intent == null) {
2591 // If the new recent task we are adding is not fully
2592 // specified, then replace it with the existing recent task.
2593 task = tr;
2594 }
2595 }
2596 }
2597 if (N >= MAX_RECENT_TASKS) {
2598 mRecentTasks.remove(N-1);
2599 }
2600 mRecentTasks.add(0, task);
2601 }
2602
2603 public void setRequestedOrientation(IBinder token,
2604 int requestedOrientation) {
2605 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002606 ActivityRecord r = mMainStack.isInStackLocked(token);
2607 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 return;
2609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002610 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002611 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002612 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002613 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002614 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 if (config != null) {
2616 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002617 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002618 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 }
2620 }
2621 Binder.restoreCallingIdentity(origId);
2622 }
2623 }
2624
2625 public int getRequestedOrientation(IBinder token) {
2626 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002627 ActivityRecord r = mMainStack.isInStackLocked(token);
2628 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2630 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002631 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 }
2633 }
2634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 /**
2636 * This is the internal entry point for handling Activity.finish().
2637 *
2638 * @param token The Binder token referencing the Activity we want to finish.
2639 * @param resultCode Result code, if any, from this Activity.
2640 * @param resultData Result data (Intent), if any, from this Activity.
2641 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002642 * @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 -08002643 */
2644 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2645 // Refuse possible leaked file descriptors
2646 if (resultData != null && resultData.hasFileDescriptors() == true) {
2647 throw new IllegalArgumentException("File descriptors passed in Intent");
2648 }
2649
2650 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002651 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002653 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 if (next != null) {
2655 // ask watcher if this is allowed
2656 boolean resumeOK = true;
2657 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002658 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002660 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 }
2662
2663 if (!resumeOK) {
2664 return false;
2665 }
2666 }
2667 }
2668 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002669 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 resultData, "app-request");
2671 Binder.restoreCallingIdentity(origId);
2672 return res;
2673 }
2674 }
2675
Dianne Hackborn860755f2010-06-03 18:47:52 -07002676 public final void finishHeavyWeightApp() {
2677 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2678 != PackageManager.PERMISSION_GRANTED) {
2679 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2680 + Binder.getCallingPid()
2681 + ", uid=" + Binder.getCallingUid()
2682 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2683 Slog.w(TAG, msg);
2684 throw new SecurityException(msg);
2685 }
2686
2687 synchronized(this) {
2688 if (mHeavyWeightProcess == null) {
2689 return;
2690 }
2691
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002692 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002693 mHeavyWeightProcess.activities);
2694 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002695 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002696 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002697 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002698 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002699 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002700 null, "finish-heavy");
2701 }
2702 }
2703 }
2704
Dianne Hackborn41203752012-08-31 14:05:51 -07002705 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2706 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002707 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002708 }
2709 }
2710
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002711 public void crashApplication(int uid, int initialPid, String packageName,
2712 String message) {
2713 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2714 != PackageManager.PERMISSION_GRANTED) {
2715 String msg = "Permission Denial: crashApplication() from pid="
2716 + Binder.getCallingPid()
2717 + ", uid=" + Binder.getCallingUid()
2718 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2719 Slog.w(TAG, msg);
2720 throw new SecurityException(msg);
2721 }
2722
2723 synchronized(this) {
2724 ProcessRecord proc = null;
2725
2726 // Figure out which process to kill. We don't trust that initialPid
2727 // still has any relation to current pids, so must scan through the
2728 // list.
2729 synchronized (mPidsSelfLocked) {
2730 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2731 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002732 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002733 continue;
2734 }
2735 if (p.pid == initialPid) {
2736 proc = p;
2737 break;
2738 }
2739 for (String str : p.pkgList) {
2740 if (str.equals(packageName)) {
2741 proc = p;
2742 }
2743 }
2744 }
2745 }
2746
2747 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002748 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002749 + " initialPid=" + initialPid
2750 + " packageName=" + packageName);
2751 return;
2752 }
2753
2754 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002755 if (proc.pid == Process.myPid()) {
2756 Log.w(TAG, "crashApplication: trying to crash self!");
2757 return;
2758 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002759 long ident = Binder.clearCallingIdentity();
2760 try {
2761 proc.thread.scheduleCrash(message);
2762 } catch (RemoteException e) {
2763 }
2764 Binder.restoreCallingIdentity(ident);
2765 }
2766 }
2767 }
2768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769 public final void finishSubActivity(IBinder token, String resultWho,
2770 int requestCode) {
2771 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002772 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002773 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002774 Binder.restoreCallingIdentity(origId);
2775 }
2776 }
2777
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002778 public boolean finishActivityAffinity(IBinder token) {
2779 synchronized(this) {
2780 final long origId = Binder.clearCallingIdentity();
2781 boolean res = mMainStack.finishActivityAffinityLocked(token);
2782 Binder.restoreCallingIdentity(origId);
2783 return res;
2784 }
2785 }
2786
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002787 public boolean willActivityBeVisible(IBinder token) {
2788 synchronized(this) {
2789 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002790 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2791 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002792 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002793 return true;
2794 }
2795 if (r.fullscreen && !r.finishing) {
2796 return false;
2797 }
2798 }
2799 return true;
2800 }
2801 }
2802
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002803 public void overridePendingTransition(IBinder token, String packageName,
2804 int enterAnim, int exitAnim) {
2805 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002806 ActivityRecord self = mMainStack.isInStackLocked(token);
2807 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002808 return;
2809 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002810
2811 final long origId = Binder.clearCallingIdentity();
2812
2813 if (self.state == ActivityState.RESUMED
2814 || self.state == ActivityState.PAUSING) {
2815 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002816 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002817 }
2818
2819 Binder.restoreCallingIdentity(origId);
2820 }
2821 }
2822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 * Main function for removing an existing process from the activity manager
2825 * as a result of that process going away. Clears out all connections
2826 * to the process.
2827 */
2828 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002829 boolean restarting, boolean allowRestart) {
2830 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002832 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 }
2834
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002835 if (mProfileProc == app) {
2836 clearProfilerLocked();
2837 }
2838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002840 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2841 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2842 mMainStack.mPausingActivity = null;
2843 }
2844 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2845 mMainStack.mLastPausedActivity = null;
2846 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847
2848 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002849 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850
2851 boolean atTop = true;
2852 boolean hasVisibleActivities = false;
2853
2854 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002855 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002856 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 TAG, "Removing app " + app + " from history with " + i + " entries");
2858 while (i > 0) {
2859 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002860 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002861 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2863 if (r.app == app) {
2864 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002865 if (ActivityStack.DEBUG_ADD_REMOVE) {
2866 RuntimeException here = new RuntimeException("here");
2867 here.fillInStackTrace();
2868 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2869 + ": haveState=" + r.haveState
2870 + " stateNotNeeded=" + r.stateNotNeeded
2871 + " finishing=" + r.finishing
2872 + " state=" + r.state, here);
2873 }
2874 if (!r.finishing) {
2875 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002876 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2877 System.identityHashCode(r),
2878 r.task.taskId, r.shortComponentName,
2879 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002880 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002881 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882
2883 } else {
2884 // We have the current state for this activity, so
2885 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002886 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002887 TAG, "Keeping entry, setting app to null");
2888 if (r.visible) {
2889 hasVisibleActivities = true;
2890 }
2891 r.app = null;
2892 r.nowVisible = false;
2893 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002894 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2895 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 r.icicle = null;
2897 }
2898 }
2899
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002900 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 }
2902 atTop = false;
2903 }
2904
2905 app.activities.clear();
2906
2907 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002908 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 + " running instrumentation " + app.instrumentationClass);
2910 Bundle info = new Bundle();
2911 info.putString("shortMsg", "Process crashed.");
2912 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2913 }
2914
2915 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002916 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 // If there was nothing to resume, and we are not already
2918 // restarting this process, but there is a visible activity that
2919 // is hosted by the process... then make sure all visible
2920 // activities are running, taking care of restarting this
2921 // process.
2922 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002923 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 }
2925 }
2926 }
2927 }
2928
2929 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2930 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002932 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2933 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2935 return i;
2936 }
2937 }
2938 return -1;
2939 }
2940
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002941 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 IApplicationThread thread) {
2943 if (thread == null) {
2944 return null;
2945 }
2946
2947 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002948 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 }
2950
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002951 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 IApplicationThread thread) {
2953
2954 mProcDeaths[0]++;
2955
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002956 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2957 synchronized (stats) {
2958 stats.noteProcessDiedLocked(app.info.uid, pid);
2959 }
2960
Magnus Edlund7bb25812010-02-24 15:45:06 +01002961 // Clean up already done if the process has been re-started.
2962 if (app.pid == pid && app.thread != null &&
2963 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002964 if (!app.killedBackground) {
2965 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2966 + ") has died.");
2967 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002968 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002969 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 TAG, "Dying app: " + app + ", pid: " + pid
2971 + ", thread: " + thread.asBinder());
2972 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002973 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974
2975 if (doLowMem) {
2976 // If there are no longer any background processes running,
2977 // and the app that died was not running instrumentation,
2978 // then tell everyone we are now low on memory.
2979 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002980 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2981 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002982 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 haveBg = true;
2984 break;
2985 }
2986 }
2987
2988 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002989 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002990 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002991 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2992 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002993 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002994 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2995 // The low memory report is overriding any current
2996 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002997 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002998 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002999 rec.lastRequestedGc = 0;
3000 } else {
3001 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003003 rec.reportLowMemory = true;
3004 rec.lastLowMemory = now;
3005 mProcessesToGc.remove(rec);
3006 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007 }
3008 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003009 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003010 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 }
3012 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003013 } else if (app.pid != pid) {
3014 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003015 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003016 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003017 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003018 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003019 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 + thread.asBinder());
3021 }
3022 }
3023
Dan Egnor42471dd2010-01-07 17:25:22 -08003024 /**
3025 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003026 * @param clearTraces causes the dump file to be erased prior to the new
3027 * traces being written, if true; when false, the new traces will be
3028 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003029 * @param firstPids of dalvik VM processes to dump stack traces for first
3030 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003031 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003032 * @return file containing stack traces, or null if no dump file is configured
3033 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003034 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003035 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003036 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3037 if (tracesPath == null || tracesPath.length() == 0) {
3038 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003039 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003040
3041 File tracesFile = new File(tracesPath);
3042 try {
3043 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003044 if (!tracesDir.exists()) {
3045 tracesFile.mkdirs();
3046 if (!SELinux.restorecon(tracesDir)) {
3047 return null;
3048 }
3049 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003050 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3051
Christopher Tate6ee412d2010-05-28 12:01:56 -07003052 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003053 tracesFile.createNewFile();
3054 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3055 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003056 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003057 return null;
3058 }
3059
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003060 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003061 return tracesFile;
3062 }
3063
3064 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003065 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003066 // Use a FileObserver to detect when traces finish writing.
3067 // The order of traces is considered important to maintain for legibility.
3068 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3069 public synchronized void onEvent(int event, String path) { notify(); }
3070 };
3071
3072 try {
3073 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003074
3075 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003076 if (firstPids != null) {
3077 try {
3078 int num = firstPids.size();
3079 for (int i = 0; i < num; i++) {
3080 synchronized (observer) {
3081 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3082 observer.wait(200); // Wait for write-close, give up after 200msec
3083 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003084 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003085 } catch (InterruptedException e) {
3086 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003087 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003088 }
3089
3090 // Next measure CPU usage.
3091 if (processStats != null) {
3092 processStats.init();
3093 System.gc();
3094 processStats.update();
3095 try {
3096 synchronized (processStats) {
3097 processStats.wait(500); // measure over 1/2 second.
3098 }
3099 } catch (InterruptedException e) {
3100 }
3101 processStats.update();
3102
3103 // We'll take the stack crawls of just the top apps using CPU.
3104 final int N = processStats.countWorkingStats();
3105 int numProcs = 0;
3106 for (int i=0; i<N && numProcs<5; i++) {
3107 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3108 if (lastPids.indexOfKey(stats.pid) >= 0) {
3109 numProcs++;
3110 try {
3111 synchronized (observer) {
3112 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3113 observer.wait(200); // Wait for write-close, give up after 200msec
3114 }
3115 } catch (InterruptedException e) {
3116 Log.wtf(TAG, e);
3117 }
3118
3119 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003120 }
3121 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003122
Dan Egnor42471dd2010-01-07 17:25:22 -08003123 } finally {
3124 observer.stopWatching();
3125 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003126
3127 if (nativeProcs != null) {
3128 int[] pids = Process.getPidsForCommands(nativeProcs);
3129 if (pids != null) {
3130 for (int pid : pids) {
3131 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3132 }
3133 }
3134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 }
3136
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003137 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003138 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003139 return;
3140 }
3141 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3142 if (tracesPath == null || tracesPath.length() == 0) {
3143 return;
3144 }
3145
3146 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3147 StrictMode.allowThreadDiskWrites();
3148 try {
3149 final File tracesFile = new File(tracesPath);
3150 final File tracesDir = tracesFile.getParentFile();
3151 final File tracesTmp = new File(tracesDir, "__tmp__");
3152 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003153 if (!tracesDir.exists()) {
3154 tracesFile.mkdirs();
3155 if (!SELinux.restorecon(tracesDir.getPath())) {
3156 return;
3157 }
3158 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003159 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3160
3161 if (tracesFile.exists()) {
3162 tracesTmp.delete();
3163 tracesFile.renameTo(tracesTmp);
3164 }
3165 StringBuilder sb = new StringBuilder();
3166 Time tobj = new Time();
3167 tobj.set(System.currentTimeMillis());
3168 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3169 sb.append(": ");
3170 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3171 sb.append(" since ");
3172 sb.append(msg);
3173 FileOutputStream fos = new FileOutputStream(tracesFile);
3174 fos.write(sb.toString().getBytes());
3175 if (app == null) {
3176 fos.write("\n*** No application process!".getBytes());
3177 }
3178 fos.close();
3179 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3180 } catch (IOException e) {
3181 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3182 return;
3183 }
3184
3185 if (app != null) {
3186 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3187 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003188 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003189 }
3190
3191 File lastTracesFile = null;
3192 File curTracesFile = null;
3193 for (int i=9; i>=0; i--) {
3194 String name = String.format("slow%02d.txt", i);
3195 curTracesFile = new File(tracesDir, name);
3196 if (curTracesFile.exists()) {
3197 if (lastTracesFile != null) {
3198 curTracesFile.renameTo(lastTracesFile);
3199 } else {
3200 curTracesFile.delete();
3201 }
3202 }
3203 lastTracesFile = curTracesFile;
3204 }
3205 tracesFile.renameTo(curTracesFile);
3206 if (tracesTmp.exists()) {
3207 tracesTmp.renameTo(tracesFile);
3208 }
3209 } finally {
3210 StrictMode.setThreadPolicy(oldPolicy);
3211 }
3212 }
3213
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003214 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3215 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003216 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3217 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3218
Dianne Hackborn287952c2010-09-22 22:34:31 -07003219 if (mController != null) {
3220 try {
3221 // 0 == continue, -1 = kill process immediately
3222 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3223 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3224 } catch (RemoteException e) {
3225 mController = null;
3226 }
3227 }
3228
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003229 long anrTime = SystemClock.uptimeMillis();
3230 if (MONITOR_CPU_USAGE) {
3231 updateCpuStatsNow();
3232 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003233
3234 synchronized (this) {
3235 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3236 if (mShuttingDown) {
3237 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3238 return;
3239 } else if (app.notResponding) {
3240 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3241 return;
3242 } else if (app.crashing) {
3243 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3244 return;
3245 }
3246
3247 // In case we come through here for the same app before completing
3248 // this one, mark as anring now so we will bail out.
3249 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003250
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003251 // Log the ANR to the event log.
3252 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3253 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003254
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003255 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003256 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003257
3258 int parentPid = app.pid;
3259 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003260 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003261
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003262 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003263
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003264 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3265 ProcessRecord r = mLruProcesses.get(i);
3266 if (r != null && r.thread != null) {
3267 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003268 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3269 if (r.persistent) {
3270 firstPids.add(pid);
3271 } else {
3272 lastPids.put(pid, Boolean.TRUE);
3273 }
3274 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 }
3277 }
3278
Dan Egnor42471dd2010-01-07 17:25:22 -08003279 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003280 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003281 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003282 info.append("ANR in ").append(app.processName);
3283 if (activity != null && activity.shortComponentName != null) {
3284 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003285 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003286 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003288 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003290 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003291 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293
Dianne Hackborn287952c2010-09-22 22:34:31 -07003294 final ProcessStats processStats = new ProcessStats(true);
3295
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003296 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003297
Dan Egnor42471dd2010-01-07 17:25:22 -08003298 String cpuInfo = null;
3299 if (MONITOR_CPU_USAGE) {
3300 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003301 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003302 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003303 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003304 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003305 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 }
3307
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003308 info.append(processStats.printCurrentState(anrTime));
3309
Joe Onorato8a9b2202010-02-26 18:56:32 -08003310 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003311 if (tracesFile == null) {
3312 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3313 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3314 }
3315
Jeff Sharkeya353d262011-10-28 11:12:06 -07003316 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3317 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003318
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003319 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003321 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3322 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003323 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003324 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3325 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 }
3327 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003328 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 }
3330 }
3331
Dan Egnor42471dd2010-01-07 17:25:22 -08003332 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3333 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3334 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003335
3336 synchronized (this) {
3337 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003338 Slog.w(TAG, "Killing " + app + ": background ANR");
3339 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3340 app.processName, app.setAdj, "background ANR");
3341 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003342 return;
3343 }
3344
3345 // Set the app's notResponding state, and look up the errorReportReceiver
3346 makeAppNotRespondingLocked(app,
3347 activity != null ? activity.shortComponentName : null,
3348 annotation != null ? "ANR " + annotation : "ANR",
3349 info.toString());
3350
3351 // Bring up the infamous App Not Responding dialog
3352 Message msg = Message.obtain();
3353 HashMap map = new HashMap();
3354 msg.what = SHOW_NOT_RESPONDING_MSG;
3355 msg.obj = map;
3356 map.put("app", app);
3357 if (activity != null) {
3358 map.put("activity", activity);
3359 }
3360
3361 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 }
3364
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003365 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3366 if (!mLaunchWarningShown) {
3367 mLaunchWarningShown = true;
3368 mHandler.post(new Runnable() {
3369 @Override
3370 public void run() {
3371 synchronized (ActivityManagerService.this) {
3372 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3373 d.show();
3374 mHandler.postDelayed(new Runnable() {
3375 @Override
3376 public void run() {
3377 synchronized (ActivityManagerService.this) {
3378 d.dismiss();
3379 mLaunchWarningShown = false;
3380 }
3381 }
3382 }, 4000);
3383 }
3384 }
3385 });
3386 }
3387 }
3388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003390 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003391 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003392 int uid = Binder.getCallingUid();
3393 int pid = Binder.getCallingPid();
3394 long callingId = Binder.clearCallingIdentity();
3395 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003396 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 int pkgUid = -1;
3398 synchronized(this) {
3399 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003400 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 } catch (RemoteException e) {
3402 }
3403 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003404 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 return false;
3406 }
3407 if (uid == pkgUid || checkComponentPermission(
3408 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003409 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003411 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 } else {
3413 throw new SecurityException(pid+" does not have permission:"+
3414 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3415 "for process:"+packageName);
3416 }
3417 }
3418
3419 try {
3420 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003421 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3423 Uri.fromParts("package", packageName, null));
3424 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003425 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003426 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 } catch (RemoteException e) {
3428 }
3429 } finally {
3430 Binder.restoreCallingIdentity(callingId);
3431 }
3432 return true;
3433 }
3434
Dianne Hackborn03abb812010-01-04 18:43:19 -08003435 public void killBackgroundProcesses(final String packageName) {
3436 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3437 != PackageManager.PERMISSION_GRANTED &&
3438 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3439 != PackageManager.PERMISSION_GRANTED) {
3440 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 + Binder.getCallingPid()
3442 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003443 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003444 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003445 throw new SecurityException(msg);
3446 }
3447
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003448 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 long callingId = Binder.clearCallingIdentity();
3450 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003451 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 int pkgUid = -1;
3453 synchronized(this) {
3454 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003455 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003456 } catch (RemoteException e) {
3457 }
3458 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003459 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 return;
3461 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003462 killPackageProcessesLocked(packageName, pkgUid, -1,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003463 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3464 }
3465 } finally {
3466 Binder.restoreCallingIdentity(callingId);
3467 }
3468 }
3469
3470 public void killAllBackgroundProcesses() {
3471 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3472 != PackageManager.PERMISSION_GRANTED) {
3473 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3474 + Binder.getCallingPid()
3475 + ", uid=" + Binder.getCallingUid()
3476 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3477 Slog.w(TAG, msg);
3478 throw new SecurityException(msg);
3479 }
3480
3481 long callingId = Binder.clearCallingIdentity();
3482 try {
3483 synchronized(this) {
3484 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3485 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3486 final int NA = apps.size();
3487 for (int ia=0; ia<NA; ia++) {
3488 ProcessRecord app = apps.valueAt(ia);
3489 if (app.persistent) {
3490 // we don't kill persistent processes
3491 continue;
3492 }
3493 if (app.removed) {
3494 procs.add(app);
3495 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3496 app.removed = true;
3497 procs.add(app);
3498 }
3499 }
3500 }
3501
3502 int N = procs.size();
3503 for (int i=0; i<N; i++) {
3504 removeProcessLocked(procs.get(i), false, true, "kill all background");
3505 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003506 }
3507 } finally {
3508 Binder.restoreCallingIdentity(callingId);
3509 }
3510 }
3511
3512 public void forceStopPackage(final String packageName) {
3513 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3514 != PackageManager.PERMISSION_GRANTED) {
3515 String msg = "Permission Denial: forceStopPackage() from pid="
3516 + Binder.getCallingPid()
3517 + ", uid=" + Binder.getCallingUid()
3518 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003519 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003520 throw new SecurityException(msg);
3521 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003522 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003523 long callingId = Binder.clearCallingIdentity();
3524 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003525 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003526 int pkgUid = -1;
3527 synchronized(this) {
3528 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003529 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003530 } catch (RemoteException e) {
3531 }
3532 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003533 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003534 return;
3535 }
3536 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003537 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003538 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003539 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003540 } catch (IllegalArgumentException e) {
3541 Slog.w(TAG, "Failed trying to unstop package "
3542 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 }
3545 } finally {
3546 Binder.restoreCallingIdentity(callingId);
3547 }
3548 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003549
3550 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003551 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003552 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003553 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003554 if (pkg == null) {
3555 return;
3556 }
3557 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003558 if (appid < 0) {
3559 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003560 return;
3561 }
3562 int callerUid = Binder.getCallingUid();
3563 // Only the system server can kill an application
3564 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003565 // Post an aysnc message to kill the application
3566 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003567 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003568 msg.arg2 = 0;
3569 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003570 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003571 } else {
3572 throw new SecurityException(callerUid + " cannot kill pkg: " +
3573 pkg);
3574 }
3575 }
3576
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003577 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003578 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003579
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003580 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003581 final int uid = Binder.getCallingUid();
3582 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003583 try {
3584 synchronized (this) {
3585 // Only allow this from foreground processes, so that background
3586 // applications can't abuse it to prevent system UI from being shown.
3587 if (uid >= Process.FIRST_APPLICATION_UID) {
3588 ProcessRecord proc;
3589 synchronized (mPidsSelfLocked) {
3590 proc = mPidsSelfLocked.get(pid);
3591 }
3592 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3593 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3594 + " from background process " + proc);
3595 return;
3596 }
3597 }
3598 closeSystemDialogsLocked(reason);
3599 }
3600 } finally {
3601 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003602 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003603 }
3604
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003605 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003606 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003607 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003608 if (reason != null) {
3609 intent.putExtra("reason", reason);
3610 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003611 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003612
Dianne Hackborne302a162012-05-15 14:58:32 -07003613 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3614 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003615 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003616 r.stack.finishActivityLocked(r, i,
3617 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003618 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003619 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003620
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003621 broadcastIntentLocked(null, null, intent, null,
3622 null, 0, null, null, null, false, false, -1,
3623 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003624 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003625
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003626 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003627 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003628 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003629 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3630 for (int i=pids.length-1; i>=0; i--) {
3631 infos[i] = new Debug.MemoryInfo();
3632 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003633 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003634 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003635 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003636
Dianne Hackbornb437e092011-08-05 17:50:29 -07003637 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003638 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003639 long[] pss = new long[pids.length];
3640 for (int i=pids.length-1; i>=0; i--) {
3641 pss[i] = Debug.getPss(pids[i]);
3642 }
3643 return pss;
3644 }
3645
Christopher Tate5e1ab332009-09-01 20:32:49 -07003646 public void killApplicationProcess(String processName, int uid) {
3647 if (processName == null) {
3648 return;
3649 }
3650
3651 int callerUid = Binder.getCallingUid();
3652 // Only the system server can kill an application
3653 if (callerUid == Process.SYSTEM_UID) {
3654 synchronized (this) {
3655 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003656 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003657 try {
3658 app.thread.scheduleSuicide();
3659 } catch (RemoteException e) {
3660 // If the other end already died, then our work here is done.
3661 }
3662 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003663 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003664 + processName + " / " + uid);
3665 }
3666 }
3667 } else {
3668 throw new SecurityException(callerUid + " cannot kill app process: " +
3669 processName);
3670 }
3671 }
3672
Dianne Hackborn03abb812010-01-04 18:43:19 -08003673 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003674 forceStopPackageLocked(packageName, uid, false, false, true, false,
3675 UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3677 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003678 if (!mProcessesReady) {
3679 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 intent.putExtra(Intent.EXTRA_UID, uid);
3682 broadcastIntentLocked(null, null, intent,
3683 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003684 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003685 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003687
3688 private void forceStopUserLocked(int userId) {
3689 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3690 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
3691 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3692 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3693 broadcastIntentLocked(null, null, intent,
3694 null, null, 0, null, null, null,
3695 false, false,
3696 MY_PID, Process.SYSTEM_UID, userId);
3697 }
3698
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003699 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003700 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3701 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003702 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703
Dianne Hackborn03abb812010-01-04 18:43:19 -08003704 // Remove all processes this package may have touched: all with the
3705 // same UID (except for the system or root user), and all whose name
3706 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003707 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003708 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3709 final int NA = apps.size();
3710 for (int ia=0; ia<NA; ia++) {
3711 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003712 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003713 // we don't kill persistent processes
3714 continue;
3715 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003716 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003717 if (doit) {
3718 procs.add(app);
3719 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003720 continue;
3721 }
3722
3723 // Skip process if it doesn't meet our oom adj requirement.
3724 if (app.setAdj < minOomAdj) {
3725 continue;
3726 }
3727
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003728 // If no package is specified, we call all processes under the
3729 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003730 if (packageName == null) {
3731 if (app.userId != userId) {
3732 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003733 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003734 // Package has been specified, we want to hit all processes
3735 // that match it. We need to qualify this by the processes
3736 // that are running under the specified app and user ID.
3737 } else {
3738 if (UserHandle.getAppId(app.uid) != appId) {
3739 continue;
3740 }
3741 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3742 continue;
3743 }
3744 if (!app.pkgList.contains(packageName)) {
3745 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003746 }
3747 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003748
3749 // Process has passed all conditions, kill it!
3750 if (!doit) {
3751 return true;
3752 }
3753 app.removed = true;
3754 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003755 }
3756 }
3757
3758 int N = procs.size();
3759 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003760 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003761 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003762 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003763 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003764
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003765 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003766 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003767 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003768 int i;
3769 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003771 if (userId == UserHandle.USER_ALL && name == null) {
3772 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3773 }
3774
3775 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003777 appId = UserHandle.getAppId(
3778 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 } catch (RemoteException e) {
3780 }
3781 }
3782
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003783 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003784 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003785 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3786 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003787 } else {
3788 Slog.i(TAG, "Force stopping user " + userId);
3789 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003790
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003791 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3792 while (badApps.hasNext()) {
3793 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003794 for (i=ba.size()-1; i>=0; i--) {
3795 boolean remove = false;
3796 final int entUid = ba.keyAt(i);
3797 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003798 if (userId == UserHandle.USER_ALL) {
3799 if (UserHandle.getAppId(entUid) == appId) {
3800 remove = true;
3801 }
3802 } else {
3803 if (entUid == UserHandle.getUid(userId, appId)) {
3804 remove = true;
3805 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003806 }
3807 } else if (UserHandle.getUserId(entUid) == userId) {
3808 remove = true;
3809 }
3810 if (remove) {
3811 ba.removeAt(i);
3812 }
3813 }
3814 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003815 badApps.remove();
3816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 }
3818 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003819
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003820 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
3821 -100, callerWillRestart, false, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003822 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003824 TaskRecord lastTask = null;
3825 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003826 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003827 final boolean samePackage = r.packageName.equals(name)
3828 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003829 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003830 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003831 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003832 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003833 if (r.finishing) {
3834 // If this activity is just finishing, then it is not
3835 // interesting as far as something to stop.
3836 continue;
3837 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003838 return true;
3839 }
3840 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003841 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003842 if (samePackage) {
3843 if (r.app != null) {
3844 r.app.removed = true;
3845 }
3846 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003848 lastTask = r.task;
3849 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003850 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003851 i--;
3852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 }
3854 }
3855
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003856 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3857 if (!doit) {
3858 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003860 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003862
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003863 if (name == null) {
3864 // Remove all sticky broadcasts from this user.
3865 mStickyBroadcasts.remove(userId);
3866 }
3867
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003868 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003869 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3870 userId, providers)) {
3871 if (!doit) {
3872 return true;
3873 }
3874 didSomething = true;
3875 }
3876 N = providers.size();
3877 for (i=0; i<N; i++) {
3878 removeDyingProviderLocked(null, providers.get(i), true);
3879 }
3880
3881 if (mIntentSenderRecords.size() > 0) {
3882 Iterator<WeakReference<PendingIntentRecord>> it
3883 = mIntentSenderRecords.values().iterator();
3884 while (it.hasNext()) {
3885 WeakReference<PendingIntentRecord> wpir = it.next();
3886 if (wpir == null) {
3887 it.remove();
3888 continue;
3889 }
3890 PendingIntentRecord pir = wpir.get();
3891 if (pir == null) {
3892 it.remove();
3893 continue;
3894 }
3895 if (name == null) {
3896 // Stopping user, remove all objects for the user.
3897 if (pir.key.userId != userId) {
3898 // Not the same user, skip it.
3899 continue;
3900 }
3901 } else {
3902 if (UserHandle.getAppId(pir.uid) != appId) {
3903 // Different app id, skip it.
3904 continue;
3905 }
3906 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3907 // Different user, skip it.
3908 continue;
3909 }
3910 if (!pir.key.packageName.equals(name)) {
3911 // Different package, skip it.
3912 continue;
3913 }
3914 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003915 if (!doit) {
3916 return true;
3917 }
3918 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003919 it.remove();
3920 pir.canceled = true;
3921 if (pir.key.activity != null) {
3922 pir.key.activity.pendingResults.remove(pir.ref);
3923 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003924 }
3925 }
3926
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003927 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003928 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003929 AttributeCache ac = AttributeCache.instance();
3930 if (ac != null) {
3931 ac.removePackage(name);
3932 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003933 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003934 if (mBooted) {
3935 mMainStack.resumeTopActivityLocked(null);
3936 mMainStack.scheduleIdleLocked();
3937 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003938 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003939
3940 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 }
3942
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003943 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003944 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003946 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003947 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003948 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 + "/" + uid + ")");
3950
3951 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003952 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003953 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07003954 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
3955 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07003956 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 boolean needRestart = false;
3959 if (app.pid > 0 && app.pid != MY_PID) {
3960 int pid = app.pid;
3961 synchronized (mPidsSelfLocked) {
3962 mPidsSelfLocked.remove(pid);
3963 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3964 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003965 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003966 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003967 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003968 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003970 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003972 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 } else {
3974 needRestart = true;
3975 }
3976 }
3977 } else {
3978 mRemovedProcesses.add(app);
3979 }
3980
3981 return needRestart;
3982 }
3983
3984 private final void processStartTimedOutLocked(ProcessRecord app) {
3985 final int pid = app.pid;
3986 boolean gone = false;
3987 synchronized (mPidsSelfLocked) {
3988 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3989 if (knownApp != null && knownApp.thread == null) {
3990 mPidsSelfLocked.remove(pid);
3991 gone = true;
3992 }
3993 }
3994
3995 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003996 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003997 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003998 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003999 mProcessNames.remove(app.processName, app.uid);
4000 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004001 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004002 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4003 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004004 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004005 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004006 // Take care of any launching providers waiting for this process.
4007 checkAppInLaunchingProvidersLocked(app, true);
4008 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004009 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004010 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
4011 app.processName, app.setAdj, "start timeout");
4012 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004013 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004014 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004015 try {
4016 IBackupManager bm = IBackupManager.Stub.asInterface(
4017 ServiceManager.getService(Context.BACKUP_SERVICE));
4018 bm.agentDisconnected(app.info.packageName);
4019 } catch (RemoteException e) {
4020 // Can't happen; the backup manager is local
4021 }
4022 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004023 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004024 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004025 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004028 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 }
4030 }
4031
4032 private final boolean attachApplicationLocked(IApplicationThread thread,
4033 int pid) {
4034
4035 // Find the application record that is being attached... either via
4036 // the pid if we are running in multiple processes, or just pull the
4037 // next app record if we are emulating process with anonymous threads.
4038 ProcessRecord app;
4039 if (pid != MY_PID && pid >= 0) {
4040 synchronized (mPidsSelfLocked) {
4041 app = mPidsSelfLocked.get(pid);
4042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 } else {
4044 app = null;
4045 }
4046
4047 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004048 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004050 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004052 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 } else {
4054 try {
4055 thread.scheduleExit();
4056 } catch (Exception e) {
4057 // Ignore exceptions.
4058 }
4059 }
4060 return false;
4061 }
4062
4063 // If this application record is still attached to a previous
4064 // process, clean it up now.
4065 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004066 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004067 }
4068
4069 // Tell the process all about itself.
4070
Joe Onorato8a9b2202010-02-26 18:56:32 -08004071 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 TAG, "Binding process pid " + pid + " to record " + app);
4073
4074 String processName = app.processName;
4075 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004076 AppDeathRecipient adr = new AppDeathRecipient(
4077 app, pid, thread);
4078 thread.asBinder().linkToDeath(adr, 0);
4079 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 } catch (RemoteException e) {
4081 app.resetPackageList();
4082 startProcessLocked(app, "link fail", processName);
4083 return false;
4084 }
4085
Doug Zongker2bec3d42009-12-04 12:52:44 -08004086 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087
4088 app.thread = thread;
4089 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004090 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4091 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 app.forcingToForeground = null;
4093 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004094 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 app.debugging = false;
4096
4097 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4098
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004099 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004100 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004102 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004103 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004104 }
4105
Joe Onorato8a9b2202010-02-26 18:56:32 -08004106 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004107 TAG, "New app record " + app
4108 + " thread=" + thread.asBinder() + " pid=" + pid);
4109 try {
4110 int testMode = IApplicationThread.DEBUG_OFF;
4111 if (mDebugApp != null && mDebugApp.equals(processName)) {
4112 testMode = mWaitForDebugger
4113 ? IApplicationThread.DEBUG_WAIT
4114 : IApplicationThread.DEBUG_ON;
4115 app.debugging = true;
4116 if (mDebugTransient) {
4117 mDebugApp = mOrigDebugApp;
4118 mWaitForDebugger = mOrigWaitForDebugger;
4119 }
4120 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004121 String profileFile = app.instrumentationProfileFile;
4122 ParcelFileDescriptor profileFd = null;
4123 boolean profileAutoStop = false;
4124 if (mProfileApp != null && mProfileApp.equals(processName)) {
4125 mProfileProc = app;
4126 profileFile = mProfileFile;
4127 profileFd = mProfileFd;
4128 profileAutoStop = mAutoStopProfiler;
4129 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004130 boolean enableOpenGlTrace = false;
4131 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4132 enableOpenGlTrace = true;
4133 mOpenGlTraceApp = null;
4134 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004135
Christopher Tate181fafa2009-05-14 11:12:14 -07004136 // If the app is being launched for restore or full backup, set it up specially
4137 boolean isRestrictedBackupMode = false;
4138 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4139 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004140 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004141 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4142 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004143
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004144 ensurePackageDexOpt(app.instrumentationInfo != null
4145 ? app.instrumentationInfo.packageName
4146 : app.info.packageName);
4147 if (app.instrumentationClass != null) {
4148 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004149 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004150 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004151 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004152 ApplicationInfo appInfo = app.instrumentationInfo != null
4153 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004154 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004155 if (profileFd != null) {
4156 profileFd = profileFd.dup();
4157 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004158 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004159 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004160 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4161 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004162 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004163 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004164 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004165 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 } catch (Exception e) {
4167 // todo: Yikes! What should we do? For now we will try to
4168 // start another process, but that could easily get us in
4169 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004170 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004171
4172 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004173 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 startProcessLocked(app, "bind fail", processName);
4175 return false;
4176 }
4177
4178 // Remove this record from the list of starting applications.
4179 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004180 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4181 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 mProcessesOnHold.remove(app);
4183
4184 boolean badApp = false;
4185 boolean didSomething = false;
4186
4187 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004188 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004189 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004190 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 && processName.equals(hr.processName)) {
4192 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004193 if (mHeadless) {
4194 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4195 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 didSomething = true;
4197 }
4198 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004199 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004200 + hr.intent.getComponent().flattenToShortString(), e);
4201 badApp = true;
4202 }
4203 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004204 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 }
4206 }
4207
4208 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004209 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004210 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004211 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213 badApp = true;
4214 }
4215 }
4216
Christopher Tatef46723b2012-01-26 14:19:24 -08004217 // Check if a next-broadcast receiver is in this process...
4218 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004219 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004220 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004221 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004222 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004224 }
4225 }
4226
Christopher Tate181fafa2009-05-14 11:12:14 -07004227 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004228 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004229 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004230 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004231 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004232 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4233 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4234 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004235 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004236 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004237 e.printStackTrace();
4238 }
4239 }
4240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 if (badApp) {
4242 // todo: Also need to kill application to deal with all
4243 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004244 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 return false;
4246 }
4247
4248 if (!didSomething) {
4249 updateOomAdjLocked();
4250 }
4251
4252 return true;
4253 }
4254
4255 public final void attachApplication(IApplicationThread thread) {
4256 synchronized (this) {
4257 int callingPid = Binder.getCallingPid();
4258 final long origId = Binder.clearCallingIdentity();
4259 attachApplicationLocked(thread, callingPid);
4260 Binder.restoreCallingIdentity(origId);
4261 }
4262 }
4263
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004264 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004265 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004266 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4267 if (stopProfiling) {
4268 synchronized (this) {
4269 if (mProfileProc == r.app) {
4270 if (mProfileFd != null) {
4271 try {
4272 mProfileFd.close();
4273 } catch (IOException e) {
4274 }
4275 clearProfilerLocked();
4276 }
4277 }
4278 }
4279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004280 Binder.restoreCallingIdentity(origId);
4281 }
4282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004284 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004285 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004286 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004287
4288 synchronized (this) {
4289 updateEventDispatchingLocked();
4290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 }
4292
Dianne Hackborn661cd522011-08-22 00:26:20 -07004293 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004294 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004295 mWindowManager.showBootMessage(msg, always);
4296 }
4297
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004298 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004299 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004300 final long token = Binder.clearCallingIdentity();
4301 try {
4302 synchronized (this) {
4303 if (mLockScreenShown) {
4304 mLockScreenShown = false;
4305 comeOutOfSleepIfNeededLocked();
4306 }
4307 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004308 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004309 } finally {
4310 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004311 }
4312 }
4313
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004314 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004315 IntentFilter pkgFilter = new IntentFilter();
4316 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4317 pkgFilter.addDataScheme("package");
4318 mContext.registerReceiver(new BroadcastReceiver() {
4319 @Override
4320 public void onReceive(Context context, Intent intent) {
4321 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4322 if (pkgs != null) {
4323 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004324 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004325 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4326 setResultCode(Activity.RESULT_OK);
4327 return;
4328 }
4329 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004330 }
4331 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004332 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004333 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004334
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004335 synchronized (this) {
4336 // Ensure that any processes we had put on hold are now started
4337 // up.
4338 final int NP = mProcessesOnHold.size();
4339 if (NP > 0) {
4340 ArrayList<ProcessRecord> procs =
4341 new ArrayList<ProcessRecord>(mProcessesOnHold);
4342 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004343 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4344 + procs.get(ip));
4345 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004346 }
4347 }
4348
4349 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004350 // Start looking for apps that are abusing wake locks.
4351 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004352 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004353 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004354 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004355 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004356 for (int i=0; i<mStartedUsers.size(); i++) {
4357 UserStartedState uss = mStartedUsers.valueAt(i);
4358 if (uss.mState == UserStartedState.STATE_BOOTING) {
4359 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004360 final int userId = mStartedUsers.keyAt(i);
4361 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4362 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4363 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004364 null, null, 0, null, null,
4365 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004366 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004367 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004368 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004369 }
4370 }
4371 }
4372
4373 final void ensureBootCompleted() {
4374 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004375 boolean enableScreen;
4376 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004377 booting = mBooting;
4378 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004379 enableScreen = !mBooted;
4380 mBooted = true;
4381 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004382
4383 if (booting) {
4384 finishBooting();
4385 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004386
4387 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004388 enableScreenAfterBoot();
4389 }
4390 }
4391
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004392 public final void activityPaused(IBinder token) {
4393 final long origId = Binder.clearCallingIdentity();
4394 mMainStack.activityPaused(token, false);
4395 Binder.restoreCallingIdentity(origId);
4396 }
4397
4398 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4399 CharSequence description) {
4400 if (localLOGV) Slog.v(
4401 TAG, "Activity stopped: token=" + token);
4402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 // Refuse possible leaked file descriptors
4404 if (icicle != null && icicle.hasFileDescriptors()) {
4405 throw new IllegalArgumentException("File descriptors passed in Bundle");
4406 }
4407
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004408 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004409
4410 final long origId = Binder.clearCallingIdentity();
4411
4412 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004413 r = mMainStack.isInStackLocked(token);
4414 if (r != null) {
4415 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004416 }
4417 }
4418
4419 if (r != null) {
4420 sendPendingThumbnail(r, null, null, null, false);
4421 }
4422
4423 trimApplications();
4424
4425 Binder.restoreCallingIdentity(origId);
4426 }
4427
4428 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004429 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004430 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004431 }
4432
4433 public String getCallingPackage(IBinder token) {
4434 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004435 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004436 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004437 }
4438 }
4439
4440 public ComponentName getCallingActivity(IBinder token) {
4441 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004442 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004443 return r != null ? r.intent.getComponent() : null;
4444 }
4445 }
4446
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004447 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004448 ActivityRecord r = mMainStack.isInStackLocked(token);
4449 if (r == null) {
4450 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004451 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004452 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453 }
4454
4455 public ComponentName getActivityClassForToken(IBinder token) {
4456 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004457 ActivityRecord r = mMainStack.isInStackLocked(token);
4458 if (r == null) {
4459 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004460 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004461 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004462 }
4463 }
4464
4465 public String getPackageForToken(IBinder token) {
4466 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004467 ActivityRecord r = mMainStack.isInStackLocked(token);
4468 if (r == null) {
4469 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004470 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004471 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004472 }
4473 }
4474
4475 public IIntentSender getIntentSender(int type,
4476 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004477 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004478 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004479 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004481 if (intents != null) {
4482 if (intents.length < 1) {
4483 throw new IllegalArgumentException("Intents array length must be >= 1");
4484 }
4485 for (int i=0; i<intents.length; i++) {
4486 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004487 if (intent != null) {
4488 if (intent.hasFileDescriptors()) {
4489 throw new IllegalArgumentException("File descriptors passed in Intent");
4490 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004491 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004492 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4493 throw new IllegalArgumentException(
4494 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4495 }
4496 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004497 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004498 }
4499 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004500 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004501 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004502 }
4503 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004504 if (options != null) {
4505 if (options.hasFileDescriptors()) {
4506 throw new IllegalArgumentException("File descriptors passed in options");
4507 }
4508 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 synchronized(this) {
4511 int callingUid = Binder.getCallingUid();
Dianne Hackborn41203752012-08-31 14:05:51 -07004512 userId = handleIncomingUserLocked(Binder.getCallingPid(), callingUid, userId,
4513 false, true, "getIntentSender", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004514 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004515 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004516 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004517 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4518 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004519 String msg = "Permission Denial: getIntentSender() from pid="
4520 + Binder.getCallingPid()
4521 + ", uid=" + Binder.getCallingUid()
4522 + ", (need uid=" + uid + ")"
4523 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004524 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 throw new SecurityException(msg);
4526 }
4527 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004528
4529 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004530 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 } catch (RemoteException e) {
4533 throw new SecurityException(e);
4534 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004535 }
4536 }
4537
Dianne Hackborn41203752012-08-31 14:05:51 -07004538 IIntentSender getIntentSenderLocked(int type, String packageName,
4539 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004540 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4541 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004542 if (DEBUG_MU)
4543 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004544 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004545 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004546 activity = mMainStack.isInStackLocked(token);
4547 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004548 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004549 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004550 if (activity.finishing) {
4551 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004553 }
4554
4555 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4556 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4557 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4558 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4559 |PendingIntent.FLAG_UPDATE_CURRENT);
4560
4561 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4562 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004563 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004564 WeakReference<PendingIntentRecord> ref;
4565 ref = mIntentSenderRecords.get(key);
4566 PendingIntentRecord rec = ref != null ? ref.get() : null;
4567 if (rec != null) {
4568 if (!cancelCurrent) {
4569 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004570 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004571 rec.key.requestIntent.replaceExtras(intents != null ?
4572 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004573 }
4574 if (intents != null) {
4575 intents[intents.length-1] = rec.key.requestIntent;
4576 rec.key.allIntents = intents;
4577 rec.key.allResolvedTypes = resolvedTypes;
4578 } else {
4579 rec.key.allIntents = null;
4580 rec.key.allResolvedTypes = null;
4581 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004583 return rec;
4584 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004585 rec.canceled = true;
4586 mIntentSenderRecords.remove(key);
4587 }
4588 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004589 return rec;
4590 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004591 rec = new PendingIntentRecord(this, key, callingUid);
4592 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004593 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004594 if (activity.pendingResults == null) {
4595 activity.pendingResults
4596 = new HashSet<WeakReference<PendingIntentRecord>>();
4597 }
4598 activity.pendingResults.add(rec.ref);
4599 }
4600 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004601 }
4602
4603 public void cancelIntentSender(IIntentSender sender) {
4604 if (!(sender instanceof PendingIntentRecord)) {
4605 return;
4606 }
4607 synchronized(this) {
4608 PendingIntentRecord rec = (PendingIntentRecord)sender;
4609 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004610 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004611 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4612 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613 String msg = "Permission Denial: cancelIntentSender() from pid="
4614 + Binder.getCallingPid()
4615 + ", uid=" + Binder.getCallingUid()
4616 + " is not allowed to cancel packges "
4617 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004618 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004619 throw new SecurityException(msg);
4620 }
4621 } catch (RemoteException e) {
4622 throw new SecurityException(e);
4623 }
4624 cancelIntentSenderLocked(rec, true);
4625 }
4626 }
4627
4628 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4629 rec.canceled = true;
4630 mIntentSenderRecords.remove(rec.key);
4631 if (cleanActivity && rec.key.activity != null) {
4632 rec.key.activity.pendingResults.remove(rec.ref);
4633 }
4634 }
4635
4636 public String getPackageForIntentSender(IIntentSender pendingResult) {
4637 if (!(pendingResult instanceof PendingIntentRecord)) {
4638 return null;
4639 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004640 try {
4641 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4642 return res.key.packageName;
4643 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004644 }
4645 return null;
4646 }
4647
Christopher Tatec4a07d12012-04-06 14:19:13 -07004648 public int getUidForIntentSender(IIntentSender sender) {
4649 if (sender instanceof PendingIntentRecord) {
4650 try {
4651 PendingIntentRecord res = (PendingIntentRecord)sender;
4652 return res.uid;
4653 } catch (ClassCastException e) {
4654 }
4655 }
4656 return -1;
4657 }
4658
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004659 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4660 if (!(pendingResult instanceof PendingIntentRecord)) {
4661 return false;
4662 }
4663 try {
4664 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4665 if (res.key.allIntents == null) {
4666 return false;
4667 }
4668 for (int i=0; i<res.key.allIntents.length; i++) {
4669 Intent intent = res.key.allIntents[i];
4670 if (intent.getPackage() != null && intent.getComponent() != null) {
4671 return false;
4672 }
4673 }
4674 return true;
4675 } catch (ClassCastException e) {
4676 }
4677 return false;
4678 }
4679
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004680 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4681 if (!(pendingResult instanceof PendingIntentRecord)) {
4682 return false;
4683 }
4684 try {
4685 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4686 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4687 return true;
4688 }
4689 return false;
4690 } catch (ClassCastException e) {
4691 }
4692 return false;
4693 }
4694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004695 public void setProcessLimit(int max) {
4696 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4697 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004698 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004699 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004700 mProcessLimitOverride = max;
4701 }
4702 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004703 }
4704
4705 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004706 synchronized (this) {
4707 return mProcessLimitOverride;
4708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004709 }
4710
4711 void foregroundTokenDied(ForegroundToken token) {
4712 synchronized (ActivityManagerService.this) {
4713 synchronized (mPidsSelfLocked) {
4714 ForegroundToken cur
4715 = mForegroundProcesses.get(token.pid);
4716 if (cur != token) {
4717 return;
4718 }
4719 mForegroundProcesses.remove(token.pid);
4720 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4721 if (pr == null) {
4722 return;
4723 }
4724 pr.forcingToForeground = null;
4725 pr.foregroundServices = false;
4726 }
4727 updateOomAdjLocked();
4728 }
4729 }
4730
4731 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4732 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4733 "setProcessForeground()");
4734 synchronized(this) {
4735 boolean changed = false;
4736
4737 synchronized (mPidsSelfLocked) {
4738 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004739 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004740 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004741 return;
4742 }
4743 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4744 if (oldToken != null) {
4745 oldToken.token.unlinkToDeath(oldToken, 0);
4746 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004747 if (pr != null) {
4748 pr.forcingToForeground = null;
4749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004750 changed = true;
4751 }
4752 if (isForeground && token != null) {
4753 ForegroundToken newToken = new ForegroundToken() {
4754 public void binderDied() {
4755 foregroundTokenDied(this);
4756 }
4757 };
4758 newToken.pid = pid;
4759 newToken.token = token;
4760 try {
4761 token.linkToDeath(newToken, 0);
4762 mForegroundProcesses.put(pid, newToken);
4763 pr.forcingToForeground = token;
4764 changed = true;
4765 } catch (RemoteException e) {
4766 // If the process died while doing this, we will later
4767 // do the cleanup with the process death link.
4768 }
4769 }
4770 }
4771
4772 if (changed) {
4773 updateOomAdjLocked();
4774 }
4775 }
4776 }
4777
4778 // =========================================================
4779 // PERMISSIONS
4780 // =========================================================
4781
4782 static class PermissionController extends IPermissionController.Stub {
4783 ActivityManagerService mActivityManagerService;
4784 PermissionController(ActivityManagerService activityManagerService) {
4785 mActivityManagerService = activityManagerService;
4786 }
4787
4788 public boolean checkPermission(String permission, int pid, int uid) {
4789 return mActivityManagerService.checkPermission(permission, pid,
4790 uid) == PackageManager.PERMISSION_GRANTED;
4791 }
4792 }
4793
4794 /**
4795 * This can be called with or without the global lock held.
4796 */
4797 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004798 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004799 // We might be performing an operation on behalf of an indirect binder
4800 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4801 // client identity accordingly before proceeding.
4802 Identity tlsIdentity = sCallerIdentity.get();
4803 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004804 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004805 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4806 uid = tlsIdentity.uid;
4807 pid = tlsIdentity.pid;
4808 }
4809
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004810 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004811 return PackageManager.PERMISSION_GRANTED;
4812 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004813
4814 return ActivityManager.checkComponentPermission(permission, uid,
4815 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004816 }
4817
4818 /**
4819 * As the only public entry point for permissions checking, this method
4820 * can enforce the semantic that requesting a check on a null global
4821 * permission is automatically denied. (Internally a null permission
4822 * string is used when calling {@link #checkComponentPermission} in cases
4823 * when only uid-based security is needed.)
4824 *
4825 * This can be called with or without the global lock held.
4826 */
4827 public int checkPermission(String permission, int pid, int uid) {
4828 if (permission == null) {
4829 return PackageManager.PERMISSION_DENIED;
4830 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004831 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004832 }
4833
4834 /**
4835 * Binder IPC calls go through the public entry point.
4836 * This can be called with or without the global lock held.
4837 */
4838 int checkCallingPermission(String permission) {
4839 return checkPermission(permission,
4840 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004841 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004842 }
4843
4844 /**
4845 * This can be called with or without the global lock held.
4846 */
4847 void enforceCallingPermission(String permission, String func) {
4848 if (checkCallingPermission(permission)
4849 == PackageManager.PERMISSION_GRANTED) {
4850 return;
4851 }
4852
4853 String msg = "Permission Denial: " + func + " from pid="
4854 + Binder.getCallingPid()
4855 + ", uid=" + Binder.getCallingUid()
4856 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004857 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004858 throw new SecurityException(msg);
4859 }
4860
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004861 /**
4862 * Determine if UID is holding permissions required to access {@link Uri} in
4863 * the given {@link ProviderInfo}. Final permission checking is always done
4864 * in {@link ContentProvider}.
4865 */
4866 private final boolean checkHoldingPermissionsLocked(
4867 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004868 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4869 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004870
4871 if (pi.applicationInfo.uid == uid) {
4872 return true;
4873 } else if (!pi.exported) {
4874 return false;
4875 }
4876
4877 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4878 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004879 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004880 // check if target holds top-level <provider> permissions
4881 if (!readMet && pi.readPermission != null
4882 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4883 readMet = true;
4884 }
4885 if (!writeMet && pi.writePermission != null
4886 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4887 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004888 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004889
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004890 // track if unprotected read/write is allowed; any denied
4891 // <path-permission> below removes this ability
4892 boolean allowDefaultRead = pi.readPermission == null;
4893 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004894
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004895 // check if target holds any <path-permission> that match uri
4896 final PathPermission[] pps = pi.pathPermissions;
4897 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004898 final String path = uri.getPath();
4899 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004900 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004901 i--;
4902 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004903 if (pp.match(path)) {
4904 if (!readMet) {
4905 final String pprperm = pp.getReadPermission();
4906 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4907 + pprperm + " for " + pp.getPath()
4908 + ": match=" + pp.match(path)
4909 + " check=" + pm.checkUidPermission(pprperm, uid));
4910 if (pprperm != null) {
4911 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4912 readMet = true;
4913 } else {
4914 allowDefaultRead = false;
4915 }
4916 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004917 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004918 if (!writeMet) {
4919 final String ppwperm = pp.getWritePermission();
4920 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4921 + ppwperm + " for " + pp.getPath()
4922 + ": match=" + pp.match(path)
4923 + " check=" + pm.checkUidPermission(ppwperm, uid));
4924 if (ppwperm != null) {
4925 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4926 writeMet = true;
4927 } else {
4928 allowDefaultWrite = false;
4929 }
4930 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004931 }
4932 }
4933 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004934 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004935
4936 // grant unprotected <provider> read/write, if not blocked by
4937 // <path-permission> above
4938 if (allowDefaultRead) readMet = true;
4939 if (allowDefaultWrite) writeMet = true;
4940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004941 } catch (RemoteException e) {
4942 return false;
4943 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004944
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004945 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004946 }
4947
4948 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4949 int modeFlags) {
4950 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004951 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004952 return true;
4953 }
4954 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4955 if (perms == null) return false;
4956 UriPermission perm = perms.get(uri);
4957 if (perm == null) return false;
4958 return (modeFlags&perm.modeFlags) == modeFlags;
4959 }
4960
4961 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004962 enforceNotIsolatedCaller("checkUriPermission");
4963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964 // Another redirected-binder-call permissions check as in
4965 // {@link checkComponentPermission}.
4966 Identity tlsIdentity = sCallerIdentity.get();
4967 if (tlsIdentity != null) {
4968 uid = tlsIdentity.uid;
4969 pid = tlsIdentity.pid;
4970 }
4971
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004972 uid = UserHandle.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004973 // Our own process gets to do everything.
4974 if (pid == MY_PID) {
4975 return PackageManager.PERMISSION_GRANTED;
4976 }
4977 synchronized(this) {
4978 return checkUriPermissionLocked(uri, uid, modeFlags)
4979 ? PackageManager.PERMISSION_GRANTED
4980 : PackageManager.PERMISSION_DENIED;
4981 }
4982 }
4983
Dianne Hackborn39792d22010-08-19 18:01:52 -07004984 /**
4985 * Check if the targetPkg can be granted permission to access uri by
4986 * the callingUid using the given modeFlags. Throws a security exception
4987 * if callingUid is not allowed to do this. Returns the uid of the target
4988 * if the URI permission grant should be performed; returns -1 if it is not
4989 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004990 * If you already know the uid of the target, you can supply it in
4991 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004992 */
4993 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004994 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004995 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4996 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4997 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004998 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004999 }
5000
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005001 if (targetPkg != null) {
5002 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5003 "Checking grant " + targetPkg + " permission to " + uri);
5004 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005005
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005006 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005007
5008 // If this is not a content: uri, we can't do anything with it.
5009 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005010 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005011 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005012 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005013 }
5014
5015 String name = uri.getAuthority();
5016 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005017 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005018 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005019 if (cpr != null) {
5020 pi = cpr.info;
5021 } else {
5022 try {
5023 pi = pm.resolveContentProvider(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005024 PackageManager.GET_URI_PERMISSION_PATTERNS, UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005025 } catch (RemoteException ex) {
5026 }
5027 }
5028 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005029 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005030 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005031 }
5032
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005033 int targetUid = lastTargetUid;
5034 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005035 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005036 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005037 if (targetUid < 0) {
5038 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5039 "Can't grant URI permission no uid for: " + targetPkg);
5040 return -1;
5041 }
5042 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005043 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005045 }
5046
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005047 if (targetUid >= 0) {
5048 // First... does the target actually need this permission?
5049 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5050 // No need to grant the target this permission.
5051 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5052 "Target " + targetPkg + " already has full permission to " + uri);
5053 return -1;
5054 }
5055 } else {
5056 // First... there is no target package, so can anyone access it?
5057 boolean allowed = pi.exported;
5058 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5059 if (pi.readPermission != null) {
5060 allowed = false;
5061 }
5062 }
5063 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5064 if (pi.writePermission != null) {
5065 allowed = false;
5066 }
5067 }
5068 if (allowed) {
5069 return -1;
5070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005071 }
5072
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005073 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005074 if (!pi.grantUriPermissions) {
5075 throw new SecurityException("Provider " + pi.packageName
5076 + "/" + pi.name
5077 + " does not allow granting of Uri permissions (uri "
5078 + uri + ")");
5079 }
5080 if (pi.uriPermissionPatterns != null) {
5081 final int N = pi.uriPermissionPatterns.length;
5082 boolean allowed = false;
5083 for (int i=0; i<N; i++) {
5084 if (pi.uriPermissionPatterns[i] != null
5085 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5086 allowed = true;
5087 break;
5088 }
5089 }
5090 if (!allowed) {
5091 throw new SecurityException("Provider " + pi.packageName
5092 + "/" + pi.name
5093 + " does not allow granting of permission to path of Uri "
5094 + uri);
5095 }
5096 }
5097
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005098 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005099 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005100 if (callingUid != Process.myUid()) {
5101 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5102 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5103 throw new SecurityException("Uid " + callingUid
5104 + " does not have permission to uri " + uri);
5105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005106 }
5107 }
5108
Dianne Hackborn39792d22010-08-19 18:01:52 -07005109 return targetUid;
5110 }
5111
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005112 public int checkGrantUriPermission(int callingUid, String targetPkg,
5113 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005114 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005115 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005116 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005117 }
5118 }
5119
Dianne Hackborn39792d22010-08-19 18:01:52 -07005120 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5121 Uri uri, int modeFlags, UriPermissionOwner owner) {
5122 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5123 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5124 if (modeFlags == 0) {
5125 return;
5126 }
5127
5128 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005129 // to the uri, and the target doesn't. Let's now give this to
5130 // the target.
5131
Joe Onorato8a9b2202010-02-26 18:56:32 -08005132 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005133 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005135 HashMap<Uri, UriPermission> targetUris
5136 = mGrantedUriPermissions.get(targetUid);
5137 if (targetUris == null) {
5138 targetUris = new HashMap<Uri, UriPermission>();
5139 mGrantedUriPermissions.put(targetUid, targetUris);
5140 }
5141
5142 UriPermission perm = targetUris.get(uri);
5143 if (perm == null) {
5144 perm = new UriPermission(targetUid, uri);
5145 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005146 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005149 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005150 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005151 } else {
5152 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5153 perm.readOwners.add(owner);
5154 owner.addReadPermission(perm);
5155 }
5156 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5157 perm.writeOwners.add(owner);
5158 owner.addWritePermission(perm);
5159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005160 }
5161 }
5162
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005163 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5164 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005165 if (targetPkg == null) {
5166 throw new NullPointerException("targetPkg");
5167 }
5168
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005169 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005170 if (targetUid < 0) {
5171 return;
5172 }
5173
5174 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5175 }
5176
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005177 static class NeededUriGrants extends ArrayList<Uri> {
5178 final String targetPkg;
5179 final int targetUid;
5180 final int flags;
5181
5182 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5183 targetPkg = _targetPkg;
5184 targetUid = _targetUid;
5185 flags = _flags;
5186 }
5187 }
5188
Dianne Hackborn39792d22010-08-19 18:01:52 -07005189 /**
5190 * Like checkGrantUriPermissionLocked, but takes an Intent.
5191 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005192 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5193 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005194 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005195 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5196 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005197 + " from " + intent + "; flags=0x"
5198 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5199
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005200 if (targetPkg == null) {
5201 throw new NullPointerException("targetPkg");
5202 }
5203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005204 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005205 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005206 }
5207 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005208 ClipData clip = intent.getClipData();
5209 if (data == null && clip == null) {
5210 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005211 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005212 if (data != null) {
5213 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5214 mode, needed != null ? needed.targetUid : -1);
5215 if (target > 0) {
5216 if (needed == null) {
5217 needed = new NeededUriGrants(targetPkg, target, mode);
5218 }
5219 needed.add(data);
5220 }
5221 }
5222 if (clip != null) {
5223 for (int i=0; i<clip.getItemCount(); i++) {
5224 Uri uri = clip.getItemAt(i).getUri();
5225 if (uri != null) {
5226 int target = -1;
5227 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5228 mode, needed != null ? needed.targetUid : -1);
5229 if (target > 0) {
5230 if (needed == null) {
5231 needed = new NeededUriGrants(targetPkg, target, mode);
5232 }
5233 needed.add(uri);
5234 }
5235 } else {
5236 Intent clipIntent = clip.getItemAt(i).getIntent();
5237 if (clipIntent != null) {
5238 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5239 callingUid, targetPkg, clipIntent, mode, needed);
5240 if (newNeeded != null) {
5241 needed = newNeeded;
5242 }
5243 }
5244 }
5245 }
5246 }
5247
5248 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005249 }
5250
5251 /**
5252 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5253 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005254 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5255 UriPermissionOwner owner) {
5256 if (needed != null) {
5257 for (int i=0; i<needed.size(); i++) {
5258 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5259 needed.get(i), needed.flags, owner);
5260 }
5261 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005262 }
5263
5264 void grantUriPermissionFromIntentLocked(int callingUid,
5265 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005266 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005267 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005268 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005269 return;
5270 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005271
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005272 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 }
5274
5275 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5276 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005277 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005278 synchronized(this) {
5279 final ProcessRecord r = getRecordForAppLocked(caller);
5280 if (r == null) {
5281 throw new SecurityException("Unable to find app for caller "
5282 + caller
5283 + " when granting permission to uri " + uri);
5284 }
5285 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005286 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005287 }
5288 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005289 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005290 }
5291
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005292 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005293 null);
5294 }
5295 }
5296
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005297 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005298 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5299 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5300 HashMap<Uri, UriPermission> perms
5301 = mGrantedUriPermissions.get(perm.uid);
5302 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005303 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005304 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005305 perms.remove(perm.uri);
5306 if (perms.size() == 0) {
5307 mGrantedUriPermissions.remove(perm.uid);
5308 }
5309 }
5310 }
5311 }
5312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005313 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5314 int modeFlags) {
5315 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5316 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5317 if (modeFlags == 0) {
5318 return;
5319 }
5320
Joe Onorato8a9b2202010-02-26 18:56:32 -08005321 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005322 "Revoking all granted permissions to " + uri);
5323
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005324 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005325
5326 final String authority = uri.getAuthority();
5327 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005328 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005329 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005330 if (cpr != null) {
5331 pi = cpr.info;
5332 } else {
5333 try {
5334 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005335 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005336 } catch (RemoteException ex) {
5337 }
5338 }
5339 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005340 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005341 return;
5342 }
5343
5344 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005345 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005346 // Right now, if you are not the original owner of the permission,
5347 // you are not allowed to revoke it.
5348 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5349 throw new SecurityException("Uid " + callingUid
5350 + " does not have permission to uri " + uri);
5351 //}
5352 }
5353
5354 // Go through all of the permissions and remove any that match.
5355 final List<String> SEGMENTS = uri.getPathSegments();
5356 if (SEGMENTS != null) {
5357 final int NS = SEGMENTS.size();
5358 int N = mGrantedUriPermissions.size();
5359 for (int i=0; i<N; i++) {
5360 HashMap<Uri, UriPermission> perms
5361 = mGrantedUriPermissions.valueAt(i);
5362 Iterator<UriPermission> it = perms.values().iterator();
5363 toploop:
5364 while (it.hasNext()) {
5365 UriPermission perm = it.next();
5366 Uri targetUri = perm.uri;
5367 if (!authority.equals(targetUri.getAuthority())) {
5368 continue;
5369 }
5370 List<String> targetSegments = targetUri.getPathSegments();
5371 if (targetSegments == null) {
5372 continue;
5373 }
5374 if (targetSegments.size() < NS) {
5375 continue;
5376 }
5377 for (int j=0; j<NS; j++) {
5378 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5379 continue toploop;
5380 }
5381 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005382 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005383 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005384 perm.clearModes(modeFlags);
5385 if (perm.modeFlags == 0) {
5386 it.remove();
5387 }
5388 }
5389 if (perms.size() == 0) {
5390 mGrantedUriPermissions.remove(
5391 mGrantedUriPermissions.keyAt(i));
5392 N--;
5393 i--;
5394 }
5395 }
5396 }
5397 }
5398
5399 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5400 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005401 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005402 synchronized(this) {
5403 final ProcessRecord r = getRecordForAppLocked(caller);
5404 if (r == null) {
5405 throw new SecurityException("Unable to find app for caller "
5406 + caller
5407 + " when revoking permission to uri " + uri);
5408 }
5409 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005410 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005411 return;
5412 }
5413
5414 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5415 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5416 if (modeFlags == 0) {
5417 return;
5418 }
5419
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005420 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005421
5422 final String authority = uri.getAuthority();
5423 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005424 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005425 if (cpr != null) {
5426 pi = cpr.info;
5427 } else {
5428 try {
5429 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005430 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005431 } catch (RemoteException ex) {
5432 }
5433 }
5434 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005435 Slog.w(TAG, "No content provider found for permission revoke: "
5436 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005437 return;
5438 }
5439
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005440 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 }
5442 }
5443
Dianne Hackborn7e269642010-08-25 19:50:20 -07005444 @Override
5445 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005446 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005447 synchronized(this) {
5448 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5449 return owner.getExternalTokenLocked();
5450 }
5451 }
5452
5453 @Override
5454 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5455 Uri uri, int modeFlags) {
5456 synchronized(this) {
5457 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5458 if (owner == null) {
5459 throw new IllegalArgumentException("Unknown owner: " + token);
5460 }
5461 if (fromUid != Binder.getCallingUid()) {
5462 if (Binder.getCallingUid() != Process.myUid()) {
5463 // Only system code can grant URI permissions on behalf
5464 // of other users.
5465 throw new SecurityException("nice try");
5466 }
5467 }
5468 if (targetPkg == null) {
5469 throw new IllegalArgumentException("null target");
5470 }
5471 if (uri == null) {
5472 throw new IllegalArgumentException("null uri");
5473 }
5474
5475 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5476 }
5477 }
5478
5479 @Override
5480 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5481 synchronized(this) {
5482 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5483 if (owner == null) {
5484 throw new IllegalArgumentException("Unknown owner: " + token);
5485 }
5486
5487 if (uri == null) {
5488 owner.removeUriPermissionsLocked(mode);
5489 } else {
5490 owner.removeUriPermissionLocked(uri, mode);
5491 }
5492 }
5493 }
5494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5496 synchronized (this) {
5497 ProcessRecord app =
5498 who != null ? getRecordForAppLocked(who) : null;
5499 if (app == null) return;
5500
5501 Message msg = Message.obtain();
5502 msg.what = WAIT_FOR_DEBUGGER_MSG;
5503 msg.obj = app;
5504 msg.arg1 = waiting ? 1 : 0;
5505 mHandler.sendMessage(msg);
5506 }
5507 }
5508
5509 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005510 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5511 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005513 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005514 outInfo.threshold = homeAppMem;
5515 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5516 outInfo.hiddenAppThreshold = hiddenAppMem;
5517 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005518 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005519 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5520 ProcessList.VISIBLE_APP_ADJ);
5521 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5522 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 }
5524
5525 // =========================================================
5526 // TASK MANAGEMENT
5527 // =========================================================
5528
5529 public List getTasks(int maxNum, int flags,
5530 IThumbnailReceiver receiver) {
5531 ArrayList list = new ArrayList();
5532
5533 PendingThumbnailsRecord pending = null;
5534 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005535 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536
5537 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005538 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5540 + ", receiver=" + receiver);
5541
5542 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5543 != PackageManager.PERMISSION_GRANTED) {
5544 if (receiver != null) {
5545 // If the caller wants to wait for pending thumbnails,
5546 // it ain't gonna get them.
5547 try {
5548 receiver.finished();
5549 } catch (RemoteException ex) {
5550 }
5551 }
5552 String msg = "Permission Denial: getTasks() from pid="
5553 + Binder.getCallingPid()
5554 + ", uid=" + Binder.getCallingUid()
5555 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005556 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557 throw new SecurityException(msg);
5558 }
5559
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005560 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005561 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005562 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005563 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005564 TaskRecord curTask = null;
5565 int numActivities = 0;
5566 int numRunning = 0;
5567 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005568 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005570 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571
5572 // Initialize state for next task if needed.
5573 if (top == null ||
5574 (top.state == ActivityState.INITIALIZING
5575 && top.task == r.task)) {
5576 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 curTask = r.task;
5578 numActivities = numRunning = 0;
5579 }
5580
5581 // Add 'r' into the current task.
5582 numActivities++;
5583 if (r.app != null && r.app.thread != null) {
5584 numRunning++;
5585 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586
Joe Onorato8a9b2202010-02-26 18:56:32 -08005587 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005588 TAG, r.intent.getComponent().flattenToShortString()
5589 + ": task=" + r.task);
5590
5591 // If the next one is a different task, generate a new
5592 // TaskInfo entry for what we have.
5593 if (next == null || next.task != curTask) {
5594 ActivityManager.RunningTaskInfo ci
5595 = new ActivityManager.RunningTaskInfo();
5596 ci.id = curTask.taskId;
5597 ci.baseActivity = r.intent.getComponent();
5598 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005599 if (top.thumbHolder != null) {
5600 ci.description = top.thumbHolder.lastDescription;
5601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 ci.numActivities = numActivities;
5603 ci.numRunning = numRunning;
5604 //System.out.println(
5605 // "#" + maxNum + ": " + " descr=" + ci.description);
5606 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005607 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 TAG, "State=" + top.state + "Idle=" + top.idle
5609 + " app=" + top.app
5610 + " thr=" + (top.app != null ? top.app.thread : null));
5611 if (top.state == ActivityState.RESUMED
5612 || top.state == ActivityState.PAUSING) {
5613 if (top.idle && top.app != null
5614 && top.app.thread != null) {
5615 topRecord = top;
5616 topThumbnail = top.app.thread;
5617 } else {
5618 top.thumbnailNeeded = true;
5619 }
5620 }
5621 if (pending == null) {
5622 pending = new PendingThumbnailsRecord(receiver);
5623 }
5624 pending.pendingRecords.add(top);
5625 }
5626 list.add(ci);
5627 maxNum--;
5628 top = null;
5629 }
5630 }
5631
5632 if (pending != null) {
5633 mPendingThumbnails.add(pending);
5634 }
5635 }
5636
Joe Onorato8a9b2202010-02-26 18:56:32 -08005637 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638
5639 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005640 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005642 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005644 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005645 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 }
5647 }
5648
5649 if (pending == null && receiver != null) {
5650 // In this case all thumbnails were available and the client
5651 // is being asked to be told when the remaining ones come in...
5652 // which is unusually, since the top-most currently running
5653 // activity should never have a canned thumbnail! Oh well.
5654 try {
5655 receiver.finished();
5656 } catch (RemoteException ex) {
5657 }
5658 }
5659
5660 return list;
5661 }
5662
5663 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005664 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005665 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005666 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07005667 // Check if the caller is holding permissions for cross-user requests.
5668 if (checkComponentPermission(
5669 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5670 Binder.getCallingPid(), callingUid, -1, true)
5671 != PackageManager.PERMISSION_GRANTED) {
5672 String msg = "Permission Denial: "
5673 + "Request to get recent tasks for user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005674 + " but is calling from user " + UserHandle.getUserId(callingUid)
Amith Yamasani82644082012-08-03 13:09:11 -07005675 + "; this requires "
5676 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5677 Slog.w(TAG, msg);
5678 throw new SecurityException(msg);
5679 } else {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005680 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07005681 userId = mCurrentUserId;
5682 }
5683 }
5684 }
5685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005686 synchronized (this) {
5687 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5688 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005689 final boolean detailed = checkCallingPermission(
5690 android.Manifest.permission.GET_DETAILED_TASKS)
5691 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005692
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005693 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 final int N = mRecentTasks.size();
5696 ArrayList<ActivityManager.RecentTaskInfo> res
5697 = new ArrayList<ActivityManager.RecentTaskInfo>(
5698 maxNum < N ? maxNum : N);
5699 for (int i=0; i<N && maxNum > 0; i++) {
5700 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005701 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005702 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005703 // Return the entry if desired by the caller. We always return
5704 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005705 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005706 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5707 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005708
Dianne Hackborn905577f2011-09-07 18:31:28 -07005709 if (i == 0
5710 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 || (tr.intent == null)
5712 || ((tr.intent.getFlags()
5713 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5714 ActivityManager.RecentTaskInfo rti
5715 = new ActivityManager.RecentTaskInfo();
5716 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005717 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005718 rti.baseIntent = new Intent(
5719 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005720 if (!detailed) {
5721 rti.baseIntent.replaceExtras((Bundle)null);
5722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005724 rti.description = tr.lastDescription;
5725
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005726 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5727 // Check whether this activity is currently available.
5728 try {
5729 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005730 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005731 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005732 continue;
5733 }
5734 } else if (rti.baseIntent != null) {
5735 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005736 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005737 continue;
5738 }
5739 }
5740 } catch (RemoteException e) {
5741 // Will never happen.
5742 }
5743 }
5744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005745 res.add(rti);
5746 maxNum--;
5747 }
5748 }
5749 return res;
5750 }
5751 }
5752
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005753 private TaskRecord taskForIdLocked(int id) {
5754 final int N = mRecentTasks.size();
5755 for (int i=0; i<N; i++) {
5756 TaskRecord tr = mRecentTasks.get(i);
5757 if (tr.taskId == id) {
5758 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005759 }
5760 }
5761 return null;
5762 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005763
5764 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5765 synchronized (this) {
5766 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5767 "getTaskThumbnails()");
5768 TaskRecord tr = taskForIdLocked(id);
5769 if (tr != null) {
5770 return mMainStack.getTaskThumbnailsLocked(tr);
5771 }
5772 }
5773 return null;
5774 }
5775
5776 public boolean removeSubTask(int taskId, int subTaskIndex) {
5777 synchronized (this) {
5778 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5779 "removeSubTask()");
5780 long ident = Binder.clearCallingIdentity();
5781 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005782 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5783 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005784 } finally {
5785 Binder.restoreCallingIdentity(ident);
5786 }
5787 }
5788 }
5789
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005790 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5791 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005792 Intent baseIntent = new Intent(
5793 tr.intent != null ? tr.intent : tr.affinityIntent);
5794 ComponentName component = baseIntent.getComponent();
5795 if (component == null) {
5796 Slog.w(TAG, "Now component for base intent of task: " + tr);
5797 return;
5798 }
5799
5800 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005801 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005802
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005803 if (killProcesses) {
5804 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005805 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005806 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005807 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5808 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5809 for (int i=0; i<uids.size(); i++) {
5810 ProcessRecord proc = uids.valueAt(i);
5811 if (proc.userId != tr.userId) {
5812 continue;
5813 }
5814 if (!proc.pkgList.contains(pkg)) {
5815 continue;
5816 }
5817 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005818 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005819 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005820
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005821 // Kill the running processes.
5822 for (int i=0; i<procs.size(); i++) {
5823 ProcessRecord pr = procs.get(i);
5824 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5825 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5826 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5827 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005828 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005829 Process.killProcessQuiet(pr.pid);
5830 } else {
5831 pr.waitingToKill = "remove task";
5832 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005833 }
5834 }
5835 }
5836
5837 public boolean removeTask(int taskId, int flags) {
5838 synchronized (this) {
5839 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5840 "removeTask()");
5841 long ident = Binder.clearCallingIdentity();
5842 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005843 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5844 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005845 if (r != null) {
5846 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005847 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005848 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005849 } else {
5850 TaskRecord tr = null;
5851 int i=0;
5852 while (i < mRecentTasks.size()) {
5853 TaskRecord t = mRecentTasks.get(i);
5854 if (t.taskId == taskId) {
5855 tr = t;
5856 break;
5857 }
5858 i++;
5859 }
5860 if (tr != null) {
5861 if (tr.numActivities <= 0) {
5862 // Caller is just removing a recent task that is
5863 // not actively running. That is easy!
5864 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005865 cleanUpRemovedTaskLocked(tr, flags);
5866 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005867 } else {
5868 Slog.w(TAG, "removeTask: task " + taskId
5869 + " does not have activities to remove, "
5870 + " but numActivities=" + tr.numActivities
5871 + ": " + tr);
5872 }
5873 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005874 }
5875 } finally {
5876 Binder.restoreCallingIdentity(ident);
5877 }
5878 }
5879 return false;
5880 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005882 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5883 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005884 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 TaskRecord jt = startTask;
5886
5887 // First look backwards
5888 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005889 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 if (r.task != jt) {
5891 jt = r.task;
5892 if (affinity.equals(jt.affinity)) {
5893 return j;
5894 }
5895 }
5896 }
5897
5898 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005899 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 jt = startTask;
5901 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005902 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005903 if (r.task != jt) {
5904 if (affinity.equals(jt.affinity)) {
5905 return j;
5906 }
5907 jt = r.task;
5908 }
5909 }
5910
5911 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005912 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005913 return N-1;
5914 }
5915
5916 return -1;
5917 }
5918
5919 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005920 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005922 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5924 "moveTaskToFront()");
5925
5926 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005927 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5928 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005929 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005930 return;
5931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005932 final long origId = Binder.clearCallingIdentity();
5933 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005934 TaskRecord tr = taskForIdLocked(task);
5935 if (tr != null) {
5936 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5937 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005938 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005939 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5940 // Caller wants the home activity moved with it. To accomplish this,
5941 // we'll just move the home task to the top first.
5942 mMainStack.moveHomeToFrontLocked();
5943 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005944 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005945 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005947 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5948 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005949 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005950 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5951 mMainStack.mUserLeaving = true;
5952 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005953 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5954 // Caller wants the home activity moved with it. To accomplish this,
5955 // we'll just move the home task to the top first.
5956 mMainStack.moveHomeToFrontLocked();
5957 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005958 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 return;
5960 }
5961 }
5962 } finally {
5963 Binder.restoreCallingIdentity(origId);
5964 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005965 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 }
5967 }
5968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 public void moveTaskToBack(int task) {
5970 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5971 "moveTaskToBack()");
5972
5973 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005974 if (mMainStack.mResumedActivity != null
5975 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005976 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5977 Binder.getCallingUid(), "Task to back")) {
5978 return;
5979 }
5980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005982 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 Binder.restoreCallingIdentity(origId);
5984 }
5985 }
5986
5987 /**
5988 * Moves an activity, and all of the other activities within the same task, to the bottom
5989 * of the history stack. The activity's order within the task is unchanged.
5990 *
5991 * @param token A reference to the activity we wish to move
5992 * @param nonRoot If false then this only works if the activity is the root
5993 * of a task; if true it will work for any activity in a task.
5994 * @return Returns true if the move completed, false if not.
5995 */
5996 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005997 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005998 synchronized(this) {
5999 final long origId = Binder.clearCallingIdentity();
6000 int taskId = getTaskForActivityLocked(token, !nonRoot);
6001 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006002 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006003 }
6004 Binder.restoreCallingIdentity(origId);
6005 }
6006 return false;
6007 }
6008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 public void moveTaskBackwards(int task) {
6010 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6011 "moveTaskBackwards()");
6012
6013 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006014 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6015 Binder.getCallingUid(), "Task backwards")) {
6016 return;
6017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006018 final long origId = Binder.clearCallingIdentity();
6019 moveTaskBackwardsLocked(task);
6020 Binder.restoreCallingIdentity(origId);
6021 }
6022 }
6023
6024 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006025 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 }
6027
6028 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6029 synchronized(this) {
6030 return getTaskForActivityLocked(token, onlyRoot);
6031 }
6032 }
6033
6034 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006035 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 TaskRecord lastTask = null;
6037 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006038 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006039 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 if (!onlyRoot || lastTask != r.task) {
6041 return r.task.taskId;
6042 }
6043 return -1;
6044 }
6045 lastTask = r.task;
6046 }
6047
6048 return -1;
6049 }
6050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 // =========================================================
6052 // THUMBNAILS
6053 // =========================================================
6054
6055 public void reportThumbnail(IBinder token,
6056 Bitmap thumbnail, CharSequence description) {
6057 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6058 final long origId = Binder.clearCallingIdentity();
6059 sendPendingThumbnail(null, token, thumbnail, description, true);
6060 Binder.restoreCallingIdentity(origId);
6061 }
6062
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006063 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 Bitmap thumbnail, CharSequence description, boolean always) {
6065 TaskRecord task = null;
6066 ArrayList receivers = null;
6067
6068 //System.out.println("Send pending thumbnail: " + r);
6069
6070 synchronized(this) {
6071 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006072 r = mMainStack.isInStackLocked(token);
6073 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006074 return;
6075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006077 if (thumbnail == null && r.thumbHolder != null) {
6078 thumbnail = r.thumbHolder.lastThumbnail;
6079 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006080 }
6081 if (thumbnail == null && !always) {
6082 // If there is no thumbnail, and this entry is not actually
6083 // going away, then abort for now and pick up the next
6084 // thumbnail we get.
6085 return;
6086 }
6087 task = r.task;
6088
6089 int N = mPendingThumbnails.size();
6090 int i=0;
6091 while (i<N) {
6092 PendingThumbnailsRecord pr =
6093 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6094 //System.out.println("Looking in " + pr.pendingRecords);
6095 if (pr.pendingRecords.remove(r)) {
6096 if (receivers == null) {
6097 receivers = new ArrayList();
6098 }
6099 receivers.add(pr);
6100 if (pr.pendingRecords.size() == 0) {
6101 pr.finished = true;
6102 mPendingThumbnails.remove(i);
6103 N--;
6104 continue;
6105 }
6106 }
6107 i++;
6108 }
6109 }
6110
6111 if (receivers != null) {
6112 final int N = receivers.size();
6113 for (int i=0; i<N; i++) {
6114 try {
6115 PendingThumbnailsRecord pr =
6116 (PendingThumbnailsRecord)receivers.get(i);
6117 pr.receiver.newThumbnail(
6118 task != null ? task.taskId : -1, thumbnail, description);
6119 if (pr.finished) {
6120 pr.receiver.finished();
6121 }
6122 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006123 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 }
6125 }
6126 }
6127 }
6128
6129 // =========================================================
6130 // CONTENT PROVIDERS
6131 // =========================================================
6132
Jeff Brown10e89712011-07-08 18:52:57 -07006133 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6134 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006136 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006137 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006138 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 } catch (RemoteException ex) {
6140 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006141 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006142 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6143 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006144 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006145 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146 for (int i=0; i<N; i++) {
6147 ProviderInfo cpi =
6148 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006149 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6150 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006151 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006152 // This is a singleton provider, but a user besides the
6153 // default user is asking to initialize a process it runs
6154 // in... well, no, it doesn't actually run in this process,
6155 // it runs in the process of the default user. Get rid of it.
6156 providers.remove(i);
6157 N--;
6158 continue;
6159 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006160
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006161 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006162 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006163 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006164 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006165 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006167 if (DEBUG_MU)
6168 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006169 app.pubProviders.put(cpi.name, cpr);
6170 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006171 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006172 }
6173 }
6174 return providers;
6175 }
6176
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006177 /**
6178 * Check if {@link ProcessRecord} has a possible chance at accessing the
6179 * given {@link ProviderInfo}. Final permission checking is always done
6180 * in {@link ContentProvider}.
6181 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006183 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006184 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006185 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006187 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006188 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 return null;
6190 }
6191 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006192 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 == PackageManager.PERMISSION_GRANTED) {
6194 return null;
6195 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006196
6197 PathPermission[] pps = cpi.pathPermissions;
6198 if (pps != null) {
6199 int i = pps.length;
6200 while (i > 0) {
6201 i--;
6202 PathPermission pp = pps[i];
6203 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006204 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006205 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006206 return null;
6207 }
6208 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006209 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006210 == PackageManager.PERMISSION_GRANTED) {
6211 return null;
6212 }
6213 }
6214 }
6215
Dianne Hackbornb424b632010-08-18 15:59:05 -07006216 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6217 if (perms != null) {
6218 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6219 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6220 return null;
6221 }
6222 }
6223 }
6224
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006225 String msg;
6226 if (!cpi.exported) {
6227 msg = "Permission Denial: opening provider " + cpi.name
6228 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6229 + ", uid=" + callingUid + ") that is not exported from uid "
6230 + cpi.applicationInfo.uid;
6231 } else {
6232 msg = "Permission Denial: opening provider " + cpi.name
6233 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6234 + ", uid=" + callingUid + ") requires "
6235 + cpi.readPermission + " or " + cpi.writePermission;
6236 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006237 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 return msg;
6239 }
6240
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006241 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6242 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006243 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006244 for (int i=0; i<r.conProviders.size(); i++) {
6245 ContentProviderConnection conn = r.conProviders.get(i);
6246 if (conn.provider == cpr) {
6247 if (DEBUG_PROVIDER) Slog.v(TAG,
6248 "Adding provider requested by "
6249 + r.processName + " from process "
6250 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6251 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6252 if (stable) {
6253 conn.stableCount++;
6254 conn.numStableIncs++;
6255 } else {
6256 conn.unstableCount++;
6257 conn.numUnstableIncs++;
6258 }
6259 return conn;
6260 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006261 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006262 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6263 if (stable) {
6264 conn.stableCount = 1;
6265 conn.numStableIncs = 1;
6266 } else {
6267 conn.unstableCount = 1;
6268 conn.numUnstableIncs = 1;
6269 }
6270 cpr.connections.add(conn);
6271 r.conProviders.add(conn);
6272 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006273 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006274 cpr.addExternalProcessHandleLocked(externalProcessToken);
6275 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006276 }
6277
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006278 boolean decProviderCountLocked(ContentProviderConnection conn,
6279 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6280 if (conn != null) {
6281 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006282 if (DEBUG_PROVIDER) Slog.v(TAG,
6283 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006284 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006285 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006286 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6287 if (stable) {
6288 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006289 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006290 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006291 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006292 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6293 cpr.connections.remove(conn);
6294 conn.client.conProviders.remove(conn);
6295 return true;
6296 }
6297 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006298 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006299 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006300 return false;
6301 }
6302
Amith Yamasani742a6712011-05-04 14:49:28 -07006303 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006304 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006306 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 ProviderInfo cpi = null;
6308
6309 synchronized(this) {
6310 ProcessRecord r = null;
6311 if (caller != null) {
6312 r = getRecordForAppLocked(caller);
6313 if (r == null) {
6314 throw new SecurityException(
6315 "Unable to find app for caller " + caller
6316 + " (pid=" + Binder.getCallingPid()
6317 + ") when getting content provider " + name);
6318 }
Dianne Hackborn41203752012-08-31 14:05:51 -07006319 if (r.userId != userId) {
6320 throw new SecurityException("Calling requested user " + userId
6321 + " but app is user " + r.userId);
6322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 }
6324
6325 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006326 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006327 boolean providerRunning = cpr != null;
6328 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006330 String msg;
6331 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6332 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 }
6334
6335 if (r != null && cpr.canRunHere(r)) {
6336 // This provider has been published or is in the process
6337 // of being published... but it is also allowed to run
6338 // in the caller's process, so don't make a connection
6339 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006340 ContentProviderHolder holder = cpr.newHolder(null);
6341 // don't give caller the provider object, it needs
6342 // to make its own.
6343 holder.provider = null;
6344 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 }
6346
6347 final long origId = Binder.clearCallingIdentity();
6348
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006349 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006350 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006351 conn = incProviderCountLocked(r, cpr, token, stable);
6352 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006353 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006354 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006355 // make sure to count it as being accessed and thus
6356 // back up on the LRU list. This is good because
6357 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006358 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006359 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006360 }
6361
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006362 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006363 if (false) {
6364 if (cpr.name.flattenToShortString().equals(
6365 "com.android.providers.calendar/.CalendarProvider2")) {
6366 Slog.v(TAG, "****************** KILLING "
6367 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006368 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006369 }
6370 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006371 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006372 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6373 // NOTE: there is still a race here where a signal could be
6374 // pending on the process even though we managed to update its
6375 // adj level. Not sure what to do about this, but at least
6376 // the race is now smaller.
6377 if (!success) {
6378 // Uh oh... it looks like the provider's process
6379 // has been killed on us. We need to wait for a new
6380 // process to be started, and make sure its death
6381 // doesn't kill our process.
6382 Slog.i(TAG,
6383 "Existing provider " + cpr.name.flattenToShortString()
6384 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006385 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006386 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006387 if (!lastRef) {
6388 // This wasn't the last ref our process had on
6389 // the provider... we have now been killed, bail.
6390 return null;
6391 }
6392 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006393 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006394 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 }
6396
6397 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006398 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006399
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006400 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006401 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006403 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006404 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006405 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 } catch (RemoteException ex) {
6407 }
6408 if (cpi == null) {
6409 return null;
6410 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006411 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6412 cpi.name, cpi.flags);
6413 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006414 userId = 0;
6415 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006416 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006417
Dianne Hackbornb424b632010-08-18 15:59:05 -07006418 String msg;
6419 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6420 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 }
6422
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006423 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006424 && !cpi.processName.equals("system")) {
6425 // If this content provider does not run in the system
6426 // process, and the system is not yet ready to run other
6427 // processes, then fail fast instead of hanging.
6428 throw new IllegalArgumentException(
6429 "Attempt to launch content provider before system ready");
6430 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006431
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006432 // Make sure that the user who owns this provider is started. If not,
6433 // we don't want to allow it to run.
6434 if (mStartedUsers.get(userId) == null) {
6435 Slog.w(TAG, "Unable to launch app "
6436 + cpi.applicationInfo.packageName + "/"
6437 + cpi.applicationInfo.uid + " for provider "
6438 + name + ": user " + userId + " is stopped");
6439 return null;
6440 }
6441
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006442 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006443 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 final boolean firstClass = cpr == null;
6445 if (firstClass) {
6446 try {
6447 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006448 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 getApplicationInfo(
6450 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006451 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006453 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 + cpi.name);
6455 return null;
6456 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006457 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006458 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 } catch (RemoteException ex) {
6460 // pm is in same process, this will never happen.
6461 }
6462 }
6463
6464 if (r != null && cpr.canRunHere(r)) {
6465 // If this is a multiprocess provider, then just return its
6466 // info and allow the caller to instantiate it. Only do
6467 // this if the provider is the same user as the caller's
6468 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006469 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 }
6471
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006472 if (DEBUG_PROVIDER) {
6473 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006474 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006475 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006476 }
6477
6478 // This is single process, and our app is now connecting to it.
6479 // See if we are already in the process of launching this
6480 // provider.
6481 final int N = mLaunchingProviders.size();
6482 int i;
6483 for (i=0; i<N; i++) {
6484 if (mLaunchingProviders.get(i) == cpr) {
6485 break;
6486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 }
6488
6489 // If the provider is not already being launched, then get it
6490 // started.
6491 if (i >= N) {
6492 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006493
6494 try {
6495 // Content provider is now in use, its package can't be stopped.
6496 try {
6497 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006498 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006499 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006500 } catch (IllegalArgumentException e) {
6501 Slog.w(TAG, "Failed trying to unstop package "
6502 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006503 }
6504
6505 ProcessRecord proc = startProcessLocked(cpi.processName,
6506 cpr.appInfo, false, 0, "content provider",
6507 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006508 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006509 if (proc == null) {
6510 Slog.w(TAG, "Unable to launch app "
6511 + cpi.applicationInfo.packageName + "/"
6512 + cpi.applicationInfo.uid + " for provider "
6513 + name + ": process is bad");
6514 return null;
6515 }
6516 cpr.launchingApp = proc;
6517 mLaunchingProviders.add(cpr);
6518 } finally {
6519 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 }
6522
6523 // Make sure the provider is published (the same provider class
6524 // may be published under multiple names).
6525 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006526 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006528
Amith Yamasani742a6712011-05-04 14:49:28 -07006529 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006530 conn = incProviderCountLocked(r, cpr, token, stable);
6531 if (conn != null) {
6532 conn.waiting = true;
6533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006534 }
6535 }
6536
6537 // Wait for the provider to be published...
6538 synchronized (cpr) {
6539 while (cpr.provider == null) {
6540 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006541 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006542 + cpi.applicationInfo.packageName + "/"
6543 + cpi.applicationInfo.uid + " for provider "
6544 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006545 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 cpi.applicationInfo.packageName,
6547 cpi.applicationInfo.uid, name);
6548 return null;
6549 }
6550 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006551 if (DEBUG_MU) {
6552 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6553 + cpr.launchingApp);
6554 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006555 if (conn != null) {
6556 conn.waiting = true;
6557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006558 cpr.wait();
6559 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006560 } finally {
6561 if (conn != null) {
6562 conn.waiting = false;
6563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006564 }
6565 }
6566 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006567 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 }
6569
6570 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006571 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006572 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006573 if (caller == null) {
6574 String msg = "null IApplicationThread when getting content provider "
6575 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006576 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 throw new SecurityException(msg);
6578 }
6579
Dianne Hackborn41203752012-08-31 14:05:51 -07006580 return getContentProviderImpl(caller, name, null, stable,
6581 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006582 }
6583
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006584 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6585 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6586 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006587 return getContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006588 }
6589
Dianne Hackborn41203752012-08-31 14:05:51 -07006590 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6591 IBinder token, int userId) {
6592 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006593 }
6594
6595 /**
6596 * Drop a content provider from a ProcessRecord's bookkeeping
6597 * @param cpr
6598 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006599 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006600 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006601 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006602 ContentProviderConnection conn;
6603 try {
6604 conn = (ContentProviderConnection)connection;
6605 } catch (ClassCastException e) {
6606 String msg ="removeContentProvider: " + connection
6607 + " not a ContentProviderConnection";
6608 Slog.w(TAG, msg);
6609 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006610 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006611 if (conn == null) {
6612 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006614 if (decProviderCountLocked(conn, null, null, stable)) {
6615 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 }
6618 }
6619
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006620 public void removeContentProviderExternal(String name, IBinder token) {
6621 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6622 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006623 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006624 }
6625
Dianne Hackborn41203752012-08-31 14:05:51 -07006626 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006627 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006628 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 if(cpr == null) {
6630 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006631 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 return;
6633 }
6634
6635 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006636 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006637 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006638 if (localCpr.hasExternalProcessHandles()) {
6639 if (localCpr.removeExternalProcessHandleLocked(token)) {
6640 updateOomAdjLocked();
6641 } else {
6642 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6643 + " with no external reference for token: "
6644 + token + ".");
6645 }
6646 } else {
6647 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6648 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006650 }
6651 }
6652
6653 public final void publishContentProviders(IApplicationThread caller,
6654 List<ContentProviderHolder> providers) {
6655 if (providers == null) {
6656 return;
6657 }
6658
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006659 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006660 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006662 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006663 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006664 if (r == null) {
6665 throw new SecurityException(
6666 "Unable to find app for caller " + caller
6667 + " (pid=" + Binder.getCallingPid()
6668 + ") when publishing content providers");
6669 }
6670
6671 final long origId = Binder.clearCallingIdentity();
6672
6673 final int N = providers.size();
6674 for (int i=0; i<N; i++) {
6675 ContentProviderHolder src = providers.get(i);
6676 if (src == null || src.info == null || src.provider == null) {
6677 continue;
6678 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006679 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006680 if (DEBUG_MU)
6681 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006682 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006683 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006684 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 String names[] = dst.info.authority.split(";");
6686 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006687 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006688 }
6689
6690 int NL = mLaunchingProviders.size();
6691 int j;
6692 for (j=0; j<NL; j++) {
6693 if (mLaunchingProviders.get(j) == dst) {
6694 mLaunchingProviders.remove(j);
6695 j--;
6696 NL--;
6697 }
6698 }
6699 synchronized (dst) {
6700 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006701 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 dst.notifyAll();
6703 }
6704 updateOomAdjLocked(r);
6705 }
6706 }
6707
6708 Binder.restoreCallingIdentity(origId);
6709 }
6710 }
6711
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006712 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6713 ContentProviderConnection conn;
6714 try {
6715 conn = (ContentProviderConnection)connection;
6716 } catch (ClassCastException e) {
6717 String msg ="refContentProvider: " + connection
6718 + " not a ContentProviderConnection";
6719 Slog.w(TAG, msg);
6720 throw new IllegalArgumentException(msg);
6721 }
6722 if (conn == null) {
6723 throw new NullPointerException("connection is null");
6724 }
6725
6726 synchronized (this) {
6727 if (stable > 0) {
6728 conn.numStableIncs += stable;
6729 }
6730 stable = conn.stableCount + stable;
6731 if (stable < 0) {
6732 throw new IllegalStateException("stableCount < 0: " + stable);
6733 }
6734
6735 if (unstable > 0) {
6736 conn.numUnstableIncs += unstable;
6737 }
6738 unstable = conn.unstableCount + unstable;
6739 if (unstable < 0) {
6740 throw new IllegalStateException("unstableCount < 0: " + unstable);
6741 }
6742
6743 if ((stable+unstable) <= 0) {
6744 throw new IllegalStateException("ref counts can't go to zero here: stable="
6745 + stable + " unstable=" + unstable);
6746 }
6747 conn.stableCount = stable;
6748 conn.unstableCount = unstable;
6749 return !conn.dead;
6750 }
6751 }
6752
6753 public void unstableProviderDied(IBinder connection) {
6754 ContentProviderConnection conn;
6755 try {
6756 conn = (ContentProviderConnection)connection;
6757 } catch (ClassCastException e) {
6758 String msg ="refContentProvider: " + connection
6759 + " not a ContentProviderConnection";
6760 Slog.w(TAG, msg);
6761 throw new IllegalArgumentException(msg);
6762 }
6763 if (conn == null) {
6764 throw new NullPointerException("connection is null");
6765 }
6766
6767 // Safely retrieve the content provider associated with the connection.
6768 IContentProvider provider;
6769 synchronized (this) {
6770 provider = conn.provider.provider;
6771 }
6772
6773 if (provider == null) {
6774 // Um, yeah, we're way ahead of you.
6775 return;
6776 }
6777
6778 // Make sure the caller is being honest with us.
6779 if (provider.asBinder().pingBinder()) {
6780 // Er, no, still looks good to us.
6781 synchronized (this) {
6782 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6783 + " says " + conn + " died, but we don't agree");
6784 return;
6785 }
6786 }
6787
6788 // Well look at that! It's dead!
6789 synchronized (this) {
6790 if (conn.provider.provider != provider) {
6791 // But something changed... good enough.
6792 return;
6793 }
6794
6795 ProcessRecord proc = conn.provider.proc;
6796 if (proc == null || proc.thread == null) {
6797 // Seems like the process is already cleaned up.
6798 return;
6799 }
6800
6801 // As far as we're concerned, this is just like receiving a
6802 // death notification... just a bit prematurely.
6803 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6804 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006805 final long ident = Binder.clearCallingIdentity();
6806 try {
6807 appDiedLocked(proc, proc.pid, proc.thread);
6808 } finally {
6809 Binder.restoreCallingIdentity(ident);
6810 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006811 }
6812 }
6813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006814 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006815 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006816 synchronized (mSelf) {
6817 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6818 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006819 if (providers != null) {
6820 for (int i=providers.size()-1; i>=0; i--) {
6821 ProviderInfo pi = (ProviderInfo)providers.get(i);
6822 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6823 Slog.w(TAG, "Not installing system proc provider " + pi.name
6824 + ": not system .apk");
6825 providers.remove(i);
6826 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006827 }
6828 }
6829 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006830 if (providers != null) {
6831 mSystemThread.installSystemProviders(providers);
6832 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006833
6834 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006835
6836 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837 }
6838
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006839 /**
6840 * Allows app to retrieve the MIME type of a URI without having permission
6841 * to access its content provider.
6842 *
6843 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6844 *
6845 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6846 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6847 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006848 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006849 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006850 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
6851 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006852 final String name = uri.getAuthority();
6853 final long ident = Binder.clearCallingIdentity();
6854 ContentProviderHolder holder = null;
6855
6856 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006857 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006858 if (holder != null) {
6859 return holder.provider.getType(uri);
6860 }
6861 } catch (RemoteException e) {
6862 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6863 return null;
6864 } finally {
6865 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006866 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006867 }
6868 Binder.restoreCallingIdentity(ident);
6869 }
6870
6871 return null;
6872 }
6873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006874 // =========================================================
6875 // GLOBAL MANAGEMENT
6876 // =========================================================
6877
6878 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006879 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006880 String proc = customProcess != null ? customProcess : info.processName;
6881 BatteryStatsImpl.Uid.Proc ps = null;
6882 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006883 int uid = info.uid;
6884 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006885 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006886 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6887 uid = 0;
6888 while (true) {
6889 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6890 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6891 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6892 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006893 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006894 mNextIsolatedProcessUid++;
6895 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6896 // No process for this uid, use it.
6897 break;
6898 }
6899 stepsLeft--;
6900 if (stepsLeft <= 0) {
6901 return null;
6902 }
6903 }
6904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006905 synchronized (stats) {
6906 ps = stats.getProcessStatsLocked(info.uid, proc);
6907 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006908 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006909 }
6910
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006911 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6912 ProcessRecord app;
6913 if (!isolated) {
6914 app = getProcessRecordLocked(info.processName, info.uid);
6915 } else {
6916 app = null;
6917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006918
6919 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006920 app = newProcessRecordLocked(null, info, null, isolated);
6921 mProcessNames.put(info.processName, app.uid, app);
6922 if (isolated) {
6923 mIsolatedProcesses.put(app.uid, app);
6924 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006925 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006926 }
6927
Dianne Hackborne7f97212011-02-24 14:40:20 -08006928 // This package really, really can not be stopped.
6929 try {
6930 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006931 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006932 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006933 } catch (IllegalArgumentException e) {
6934 Slog.w(TAG, "Failed trying to unstop package "
6935 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006936 }
6937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006938 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6939 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6940 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006941 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006942 }
6943 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6944 mPersistentStartingProcesses.add(app);
6945 startProcessLocked(app, "added application", app.processName);
6946 }
6947
6948 return app;
6949 }
6950
6951 public void unhandledBack() {
6952 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6953 "unhandledBack()");
6954
6955 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006956 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006957 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958 TAG, "Performing unhandledBack(): stack size = " + count);
6959 if (count > 1) {
6960 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006961 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006962 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6963 Binder.restoreCallingIdentity(origId);
6964 }
6965 }
6966 }
6967
6968 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006969 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07006970 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006971 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07006972 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006973 ParcelFileDescriptor pfd = null;
6974 if (cph != null) {
6975 // We record the binder invoker's uid in thread-local storage before
6976 // going to the content provider to open the file. Later, in the code
6977 // that handles all permissions checks, we look for this uid and use
6978 // that rather than the Activity Manager's own uid. The effect is that
6979 // we do the check against the caller's permissions even though it looks
6980 // to the content provider like the Activity Manager itself is making
6981 // the request.
6982 sCallerIdentity.set(new Identity(
6983 Binder.getCallingPid(), Binder.getCallingUid()));
6984 try {
6985 pfd = cph.provider.openFile(uri, "r");
6986 } catch (FileNotFoundException e) {
6987 // do nothing; pfd will be returned null
6988 } finally {
6989 // Ensure that whatever happens, we clean up the identity state
6990 sCallerIdentity.remove();
6991 }
6992
6993 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07006994 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006995 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006996 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006997 }
6998 return pfd;
6999 }
7000
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007001 // Actually is sleeping or shutting down or whatever else in the future
7002 // is an inactive state.
7003 public boolean isSleeping() {
7004 return mSleeping || mShuttingDown;
7005 }
7006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007007 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007008 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7009 != PackageManager.PERMISSION_GRANTED) {
7010 throw new SecurityException("Requires permission "
7011 + android.Manifest.permission.DEVICE_POWER);
7012 }
7013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007014 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007015 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007016 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007018 if (!mSleeping) {
7019 mSleeping = true;
7020 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007021
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007022 // Initialize the wake times of all processes.
7023 checkExcessivePowerUsageLocked(false);
7024 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7025 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7026 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7027 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 }
7029 }
7030
Dianne Hackborn55280a92009-05-07 15:53:46 -07007031 public boolean shutdown(int timeout) {
7032 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7033 != PackageManager.PERMISSION_GRANTED) {
7034 throw new SecurityException("Requires permission "
7035 + android.Manifest.permission.SHUTDOWN);
7036 }
7037
7038 boolean timedout = false;
7039
7040 synchronized(this) {
7041 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007042 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007043
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007044 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007045 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007046 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007047 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007048 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007049 long delay = endTime - System.currentTimeMillis();
7050 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007051 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007052 timedout = true;
7053 break;
7054 }
7055 try {
7056 this.wait();
7057 } catch (InterruptedException e) {
7058 }
7059 }
7060 }
7061 }
7062
7063 mUsageStatsService.shutdown();
7064 mBatteryStatsService.shutdown();
7065
7066 return timedout;
7067 }
7068
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007069 public final void activitySlept(IBinder token) {
7070 if (localLOGV) Slog.v(
7071 TAG, "Activity slept: token=" + token);
7072
7073 ActivityRecord r = null;
7074
7075 final long origId = Binder.clearCallingIdentity();
7076
7077 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007078 r = mMainStack.isInStackLocked(token);
7079 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007080 mMainStack.activitySleptLocked(r);
7081 }
7082 }
7083
7084 Binder.restoreCallingIdentity(origId);
7085 }
7086
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007087 private void comeOutOfSleepIfNeededLocked() {
7088 if (!mWentToSleep && !mLockScreenShown) {
7089 if (mSleeping) {
7090 mSleeping = false;
7091 mMainStack.awakeFromSleepingLocked();
7092 mMainStack.resumeTopActivityLocked(null);
7093 }
7094 }
7095 }
7096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007097 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007098 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7099 != PackageManager.PERMISSION_GRANTED) {
7100 throw new SecurityException("Requires permission "
7101 + android.Manifest.permission.DEVICE_POWER);
7102 }
7103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007104 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007105 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007106 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007107 comeOutOfSleepIfNeededLocked();
7108 }
7109 }
7110
Jeff Brownc042ee22012-05-08 13:03:42 -07007111 private void updateEventDispatchingLocked() {
7112 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7113 }
7114
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007115 public void setLockScreenShown(boolean shown) {
7116 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7117 != PackageManager.PERMISSION_GRANTED) {
7118 throw new SecurityException("Requires permission "
7119 + android.Manifest.permission.DEVICE_POWER);
7120 }
7121
7122 synchronized(this) {
7123 mLockScreenShown = shown;
7124 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007125 }
7126 }
7127
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007128 public void stopAppSwitches() {
7129 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7130 != PackageManager.PERMISSION_GRANTED) {
7131 throw new SecurityException("Requires permission "
7132 + android.Manifest.permission.STOP_APP_SWITCHES);
7133 }
7134
7135 synchronized(this) {
7136 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7137 + APP_SWITCH_DELAY_TIME;
7138 mDidAppSwitch = false;
7139 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7140 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7141 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7142 }
7143 }
7144
7145 public void resumeAppSwitches() {
7146 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7147 != PackageManager.PERMISSION_GRANTED) {
7148 throw new SecurityException("Requires permission "
7149 + android.Manifest.permission.STOP_APP_SWITCHES);
7150 }
7151
7152 synchronized(this) {
7153 // Note that we don't execute any pending app switches... we will
7154 // let those wait until either the timeout, or the next start
7155 // activity request.
7156 mAppSwitchesAllowedTime = 0;
7157 }
7158 }
7159
7160 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7161 String name) {
7162 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7163 return true;
7164 }
7165
7166 final int perm = checkComponentPermission(
7167 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007168 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007169 if (perm == PackageManager.PERMISSION_GRANTED) {
7170 return true;
7171 }
7172
Joe Onorato8a9b2202010-02-26 18:56:32 -08007173 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007174 return false;
7175 }
7176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 public void setDebugApp(String packageName, boolean waitForDebugger,
7178 boolean persistent) {
7179 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7180 "setDebugApp()");
7181
7182 // Note that this is not really thread safe if there are multiple
7183 // callers into it at the same time, but that's not a situation we
7184 // care about.
7185 if (persistent) {
7186 final ContentResolver resolver = mContext.getContentResolver();
7187 Settings.System.putString(
7188 resolver, Settings.System.DEBUG_APP,
7189 packageName);
7190 Settings.System.putInt(
7191 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7192 waitForDebugger ? 1 : 0);
7193 }
7194
7195 synchronized (this) {
7196 if (!persistent) {
7197 mOrigDebugApp = mDebugApp;
7198 mOrigWaitForDebugger = mWaitForDebugger;
7199 }
7200 mDebugApp = packageName;
7201 mWaitForDebugger = waitForDebugger;
7202 mDebugTransient = !persistent;
7203 if (packageName != null) {
7204 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007205 forceStopPackageLocked(packageName, -1, false, false, true, true,
7206 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007207 Binder.restoreCallingIdentity(origId);
7208 }
7209 }
7210 }
7211
Siva Velusamy92a8b222012-03-09 16:24:04 -08007212 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7213 synchronized (this) {
7214 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7215 if (!isDebuggable) {
7216 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7217 throw new SecurityException("Process not debuggable: " + app.packageName);
7218 }
7219 }
7220
7221 mOpenGlTraceApp = processName;
7222 }
7223 }
7224
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007225 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7226 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7227 synchronized (this) {
7228 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7229 if (!isDebuggable) {
7230 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7231 throw new SecurityException("Process not debuggable: " + app.packageName);
7232 }
7233 }
7234 mProfileApp = processName;
7235 mProfileFile = profileFile;
7236 if (mProfileFd != null) {
7237 try {
7238 mProfileFd.close();
7239 } catch (IOException e) {
7240 }
7241 mProfileFd = null;
7242 }
7243 mProfileFd = profileFd;
7244 mProfileType = 0;
7245 mAutoStopProfiler = autoStopProfiler;
7246 }
7247 }
7248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007249 public void setAlwaysFinish(boolean enabled) {
7250 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7251 "setAlwaysFinish()");
7252
7253 Settings.System.putInt(
7254 mContext.getContentResolver(),
7255 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7256
7257 synchronized (this) {
7258 mAlwaysFinishActivities = enabled;
7259 }
7260 }
7261
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007262 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007263 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007264 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007266 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007267 }
7268 }
7269
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007270 public boolean isUserAMonkey() {
7271 // For now the fact that there is a controller implies
7272 // we have a monkey.
7273 synchronized (this) {
7274 return mController != null;
7275 }
7276 }
7277
Jeff Sharkeya4620792011-05-20 15:29:23 -07007278 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007279 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7280 "registerProcessObserver()");
7281 synchronized (this) {
7282 mProcessObservers.register(observer);
7283 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007284 }
7285
7286 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007287 synchronized (this) {
7288 mProcessObservers.unregister(observer);
7289 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007290 }
7291
Daniel Sandler69a48172010-06-23 16:29:36 -04007292 public void setImmersive(IBinder token, boolean immersive) {
7293 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007294 ActivityRecord r = mMainStack.isInStackLocked(token);
7295 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007296 throw new IllegalArgumentException();
7297 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007298 r.immersive = immersive;
7299 }
7300 }
7301
7302 public boolean isImmersive(IBinder token) {
7303 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007304 ActivityRecord r = mMainStack.isInStackLocked(token);
7305 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007306 throw new IllegalArgumentException();
7307 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007308 return r.immersive;
7309 }
7310 }
7311
7312 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007313 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007314 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007315 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007316 return (r != null) ? r.immersive : false;
7317 }
7318 }
7319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007320 public final void enterSafeMode() {
7321 synchronized(this) {
7322 // It only makes sense to do this before the system is ready
7323 // and started launching other packages.
7324 if (!mSystemReady) {
7325 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007326 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007327 } catch (RemoteException e) {
7328 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007329 }
7330 }
7331 }
7332
Jeff Brownb09abc12011-01-13 21:08:27 -08007333 public final void showSafeModeOverlay() {
7334 View v = LayoutInflater.from(mContext).inflate(
7335 com.android.internal.R.layout.safe_mode, null);
7336 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7337 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7338 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7339 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007340 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007341 lp.format = v.getBackground().getOpacity();
7342 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7343 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7344 ((WindowManager)mContext.getSystemService(
7345 Context.WINDOW_SERVICE)).addView(v, lp);
7346 }
7347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007348 public void noteWakeupAlarm(IIntentSender sender) {
7349 if (!(sender instanceof PendingIntentRecord)) {
7350 return;
7351 }
7352 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7353 synchronized (stats) {
7354 if (mBatteryStatsService.isOnBattery()) {
7355 mBatteryStatsService.enforceCallingPermission();
7356 PendingIntentRecord rec = (PendingIntentRecord)sender;
7357 int MY_UID = Binder.getCallingUid();
7358 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7359 BatteryStatsImpl.Uid.Pkg pkg =
7360 stats.getPackageStatsLocked(uid, rec.key.packageName);
7361 pkg.incWakeupsLocked();
7362 }
7363 }
7364 }
7365
Dianne Hackborn64825172011-03-02 21:32:58 -08007366 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007367 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007368 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007369 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007370 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007371 // XXX Note: don't acquire main activity lock here, because the window
7372 // manager calls in with its locks held.
7373
7374 boolean killed = false;
7375 synchronized (mPidsSelfLocked) {
7376 int[] types = new int[pids.length];
7377 int worstType = 0;
7378 for (int i=0; i<pids.length; i++) {
7379 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7380 if (proc != null) {
7381 int type = proc.setAdj;
7382 types[i] = type;
7383 if (type > worstType) {
7384 worstType = type;
7385 }
7386 }
7387 }
7388
Dianne Hackborn64825172011-03-02 21:32:58 -08007389 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007390 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007391 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7392 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007393 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007394 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007395
7396 // If this is not a secure call, don't let it kill processes that
7397 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007398 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7399 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007400 }
7401
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007402 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007403 for (int i=0; i<pids.length; i++) {
7404 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7405 if (proc == null) {
7406 continue;
7407 }
7408 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007409 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007410 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007411 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7412 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007413 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007414 proc.killedBackground = true;
7415 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007416 }
7417 }
7418 }
7419 return killed;
7420 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007421
7422 @Override
7423 public boolean killProcessesBelowForeground(String reason) {
7424 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7425 throw new SecurityException("killProcessesBelowForeground() only available to system");
7426 }
7427
7428 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7429 }
7430
7431 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7432 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7433 throw new SecurityException("killProcessesBelowAdj() only available to system");
7434 }
7435
7436 boolean killed = false;
7437 synchronized (mPidsSelfLocked) {
7438 final int size = mPidsSelfLocked.size();
7439 for (int i = 0; i < size; i++) {
7440 final int pid = mPidsSelfLocked.keyAt(i);
7441 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7442 if (proc == null) continue;
7443
7444 final int adj = proc.setAdj;
7445 if (adj > belowAdj && !proc.killedBackground) {
7446 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7447 EventLog.writeEvent(
7448 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7449 killed = true;
7450 proc.killedBackground = true;
7451 Process.killProcessQuiet(pid);
7452 }
7453 }
7454 }
7455 return killed;
7456 }
7457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007458 public final void startRunning(String pkg, String cls, String action,
7459 String data) {
7460 synchronized(this) {
7461 if (mStartRunning) {
7462 return;
7463 }
7464 mStartRunning = true;
7465 mTopComponent = pkg != null && cls != null
7466 ? new ComponentName(pkg, cls) : null;
7467 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7468 mTopData = data;
7469 if (!mSystemReady) {
7470 return;
7471 }
7472 }
7473
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007474 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007475 }
7476
7477 private void retrieveSettings() {
7478 final ContentResolver resolver = mContext.getContentResolver();
7479 String debugApp = Settings.System.getString(
7480 resolver, Settings.System.DEBUG_APP);
7481 boolean waitForDebugger = Settings.System.getInt(
7482 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7483 boolean alwaysFinishActivities = Settings.System.getInt(
7484 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7485
7486 Configuration configuration = new Configuration();
7487 Settings.System.getConfiguration(resolver, configuration);
7488
7489 synchronized (this) {
7490 mDebugApp = mOrigDebugApp = debugApp;
7491 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7492 mAlwaysFinishActivities = alwaysFinishActivities;
7493 // This happens before any activities are started, so we can
7494 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007495 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007496 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007497 }
7498 }
7499
7500 public boolean testIsSystemReady() {
7501 // no need to synchronize(this) just to read & return the value
7502 return mSystemReady;
7503 }
7504
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007505 private static File getCalledPreBootReceiversFile() {
7506 File dataDir = Environment.getDataDirectory();
7507 File systemDir = new File(dataDir, "system");
7508 File fname = new File(systemDir, "called_pre_boots.dat");
7509 return fname;
7510 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007511
7512 static final int LAST_DONE_VERSION = 10000;
7513
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007514 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7515 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7516 File file = getCalledPreBootReceiversFile();
7517 FileInputStream fis = null;
7518 try {
7519 fis = new FileInputStream(file);
7520 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007521 int fvers = dis.readInt();
7522 if (fvers == LAST_DONE_VERSION) {
7523 String vers = dis.readUTF();
7524 String codename = dis.readUTF();
7525 String build = dis.readUTF();
7526 if (android.os.Build.VERSION.RELEASE.equals(vers)
7527 && android.os.Build.VERSION.CODENAME.equals(codename)
7528 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7529 int num = dis.readInt();
7530 while (num > 0) {
7531 num--;
7532 String pkg = dis.readUTF();
7533 String cls = dis.readUTF();
7534 lastDoneReceivers.add(new ComponentName(pkg, cls));
7535 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007536 }
7537 }
7538 } catch (FileNotFoundException e) {
7539 } catch (IOException e) {
7540 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7541 } finally {
7542 if (fis != null) {
7543 try {
7544 fis.close();
7545 } catch (IOException e) {
7546 }
7547 }
7548 }
7549 return lastDoneReceivers;
7550 }
7551
7552 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7553 File file = getCalledPreBootReceiversFile();
7554 FileOutputStream fos = null;
7555 DataOutputStream dos = null;
7556 try {
7557 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7558 fos = new FileOutputStream(file);
7559 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007560 dos.writeInt(LAST_DONE_VERSION);
7561 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007562 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007563 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007564 dos.writeInt(list.size());
7565 for (int i=0; i<list.size(); i++) {
7566 dos.writeUTF(list.get(i).getPackageName());
7567 dos.writeUTF(list.get(i).getClassName());
7568 }
7569 } catch (IOException e) {
7570 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7571 file.delete();
7572 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007573 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007574 if (dos != null) {
7575 try {
7576 dos.close();
7577 } catch (IOException e) {
7578 // TODO Auto-generated catch block
7579 e.printStackTrace();
7580 }
7581 }
7582 }
7583 }
7584
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007585 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007586 synchronized(this) {
7587 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007588 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007589 return;
7590 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007591
7592 // Check to see if there are any update receivers to run.
7593 if (!mDidUpdate) {
7594 if (mWaitingUpdate) {
7595 return;
7596 }
7597 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7598 List<ResolveInfo> ris = null;
7599 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007600 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007601 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007602 } catch (RemoteException e) {
7603 }
7604 if (ris != null) {
7605 for (int i=ris.size()-1; i>=0; i--) {
7606 if ((ris.get(i).activityInfo.applicationInfo.flags
7607 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7608 ris.remove(i);
7609 }
7610 }
7611 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007612
7613 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7614
7615 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007616 for (int i=0; i<ris.size(); i++) {
7617 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007618 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7619 if (lastDoneReceivers.contains(comp)) {
7620 ris.remove(i);
7621 i--;
7622 }
7623 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007624
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007625 for (int i=0; i<ris.size(); i++) {
7626 ActivityInfo ai = ris.get(i).activityInfo;
7627 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7628 doneReceivers.add(comp);
7629 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007630 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007631 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007632 finisher = new IIntentReceiver.Stub() {
7633 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007634 String data, Bundle extras, boolean ordered,
Dianne Hackborn20e80982012-08-31 19:00:44 -07007635 boolean sticky, int sendingUser) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007636 // The raw IIntentReceiver interface is called
7637 // with the AM lock held, so redispatch to
7638 // execute our code without the lock.
7639 mHandler.post(new Runnable() {
7640 public void run() {
7641 synchronized (ActivityManagerService.this) {
7642 mDidUpdate = true;
7643 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007644 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007645 showBootMessage(mContext.getText(
7646 R.string.android_upgrading_complete),
7647 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007648 systemReady(goingCallback);
7649 }
7650 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007651 }
7652 };
7653 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007654 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007655 // XXX also need to send this to stopped users(!!!)
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007656 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007657 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007658 UserHandle.USER_ALL);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007659 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007660 mWaitingUpdate = true;
7661 }
7662 }
7663 }
7664 if (mWaitingUpdate) {
7665 return;
7666 }
7667 mDidUpdate = true;
7668 }
7669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670 mSystemReady = true;
7671 if (!mStartRunning) {
7672 return;
7673 }
7674 }
7675
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007676 ArrayList<ProcessRecord> procsToKill = null;
7677 synchronized(mPidsSelfLocked) {
7678 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7679 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7680 if (!isAllowedWhileBooting(proc.info)){
7681 if (procsToKill == null) {
7682 procsToKill = new ArrayList<ProcessRecord>();
7683 }
7684 procsToKill.add(proc);
7685 }
7686 }
7687 }
7688
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007689 synchronized(this) {
7690 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007691 for (int i=procsToKill.size()-1; i>=0; i--) {
7692 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007693 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007694 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007695 }
7696 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007697
7698 // Now that we have cleaned up any update processes, we
7699 // are ready to start launching real processes and know that
7700 // we won't trample on them any more.
7701 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007702 }
7703
Joe Onorato8a9b2202010-02-26 18:56:32 -08007704 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007705 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007706 SystemClock.uptimeMillis());
7707
7708 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007709 // Make sure we have no pre-ready processes sitting around.
7710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007711 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7712 ResolveInfo ri = mContext.getPackageManager()
7713 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007714 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715 CharSequence errorMsg = null;
7716 if (ri != null) {
7717 ActivityInfo ai = ri.activityInfo;
7718 ApplicationInfo app = ai.applicationInfo;
7719 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7720 mTopAction = Intent.ACTION_FACTORY_TEST;
7721 mTopData = null;
7722 mTopComponent = new ComponentName(app.packageName,
7723 ai.name);
7724 } else {
7725 errorMsg = mContext.getResources().getText(
7726 com.android.internal.R.string.factorytest_not_system);
7727 }
7728 } else {
7729 errorMsg = mContext.getResources().getText(
7730 com.android.internal.R.string.factorytest_no_action);
7731 }
7732 if (errorMsg != null) {
7733 mTopAction = null;
7734 mTopData = null;
7735 mTopComponent = null;
7736 Message msg = Message.obtain();
7737 msg.what = SHOW_FACTORY_ERROR_MSG;
7738 msg.getData().putCharSequence("msg", errorMsg);
7739 mHandler.sendMessage(msg);
7740 }
7741 }
7742 }
7743
7744 retrieveSettings();
7745
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007746 if (goingCallback != null) goingCallback.run();
7747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 synchronized (this) {
7749 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7750 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007751 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007752 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753 if (apps != null) {
7754 int N = apps.size();
7755 int i;
7756 for (i=0; i<N; i++) {
7757 ApplicationInfo info
7758 = (ApplicationInfo)apps.get(i);
7759 if (info != null &&
7760 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007761 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007762 }
7763 }
7764 }
7765 } catch (RemoteException ex) {
7766 // pm is in same process, this will never happen.
7767 }
7768 }
7769
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007770 // Start up initial activity.
7771 mBooting = true;
7772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007774 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007775 Message msg = Message.obtain();
7776 msg.what = SHOW_UID_ERROR_MSG;
7777 mHandler.sendMessage(msg);
7778 }
7779 } catch (RemoteException e) {
7780 }
7781
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007782 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 }
7784 }
7785
Dan Egnorb7f03672009-12-09 16:22:32 -08007786 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007787 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007789 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007790 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 startAppProblemLocked(app);
7792 app.stopFreezingAllLocked();
7793 return handleAppCrashLocked(app);
7794 }
7795
Dan Egnorb7f03672009-12-09 16:22:32 -08007796 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007797 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007798 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007799 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007800 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7801 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007802 startAppProblemLocked(app);
7803 app.stopFreezingAllLocked();
7804 }
7805
7806 /**
7807 * Generate a process error record, suitable for attachment to a ProcessRecord.
7808 *
7809 * @param app The ProcessRecord in which the error occurred.
7810 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7811 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007812 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007813 * @param shortMsg Short message describing the crash.
7814 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007815 * @param stackTrace Full crash stack trace, may be null.
7816 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 * @return Returns a fully-formed AppErrorStateInfo record.
7818 */
7819 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007820 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007821 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007823 report.condition = condition;
7824 report.processName = app.processName;
7825 report.pid = app.pid;
7826 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007827 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007828 report.shortMsg = shortMsg;
7829 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007830 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007831
7832 return report;
7833 }
7834
Dan Egnor42471dd2010-01-07 17:25:22 -08007835 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 synchronized (this) {
7837 app.crashing = false;
7838 app.crashingReport = null;
7839 app.notResponding = false;
7840 app.notRespondingReport = null;
7841 if (app.anrDialog == fromDialog) {
7842 app.anrDialog = null;
7843 }
7844 if (app.waitDialog == fromDialog) {
7845 app.waitDialog = null;
7846 }
7847 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007848 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007849 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007850 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7851 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007852 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007854 }
7855 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007856
Dan Egnorb7f03672009-12-09 16:22:32 -08007857 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007858 if (mHeadless) {
7859 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7860 return false;
7861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 long now = SystemClock.uptimeMillis();
7863
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007864 Long crashTime;
7865 if (!app.isolated) {
7866 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7867 } else {
7868 crashTime = null;
7869 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007870 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007871 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007872 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007873 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007874 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007875 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007876 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7877 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007878 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007879 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007880 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007881 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007882 }
7883 }
7884 if (!app.persistent) {
7885 // We don't want to start this process again until the user
7886 // explicitly does so... but for persistent process, we really
7887 // need to keep it running. If a persistent process is actually
7888 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007889 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007890 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007891 if (!app.isolated) {
7892 // XXX We don't have a way to mark isolated processes
7893 // as bad, since they don't have a peristent identity.
7894 mBadProcesses.put(app.info.processName, app.uid, now);
7895 mProcessCrashTimes.remove(app.info.processName, app.uid);
7896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007897 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007898 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007899 // Don't let services in this process be restarted and potentially
7900 // annoy the user repeatedly. Unless it is persistent, since those
7901 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007902 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007903 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007904 return false;
7905 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007906 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007907 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007908 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007909 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007910 // If the top running activity is from this crashing
7911 // process, then terminate it to avoid getting in a loop.
7912 Slog.w(TAG, " Force finishing activity "
7913 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007914 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007915 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007916 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007917 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007918 // stopped, to avoid a situation where one will get
7919 // re-start our crashing activity once it gets resumed again.
7920 index--;
7921 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007922 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007923 if (r.state == ActivityState.RESUMED
7924 || r.state == ActivityState.PAUSING
7925 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007926 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007927 Slog.w(TAG, " Force finishing activity "
7928 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007929 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007930 Activity.RESULT_CANCELED, null, "crashed");
7931 }
7932 }
7933 }
7934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007935 }
7936
7937 // Bump up the crash count of any services currently running in the proc.
7938 if (app.services.size() != 0) {
7939 // Any services running in the application need to be placed
7940 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007941 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007942 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007943 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007944 sr.crashCount++;
7945 }
7946 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007947
7948 // If the crashing process is what we consider to be the "home process" and it has been
7949 // replaced by a third-party app, clear the package preferred activities from packages
7950 // with a home activity running in the process to prevent a repeatedly crashing app
7951 // from blocking the user to manually clear the list.
7952 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7953 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7954 Iterator it = mHomeProcess.activities.iterator();
7955 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007956 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007957 if (r.isHomeActivity) {
7958 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7959 try {
7960 ActivityThread.getPackageManager()
7961 .clearPackagePreferredActivities(r.packageName);
7962 } catch (RemoteException c) {
7963 // pm is in same process, this will never happen.
7964 }
7965 }
7966 }
7967 }
7968
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007969 if (!app.isolated) {
7970 // XXX Can't keep track of crash times for isolated processes,
7971 // because they don't have a perisistent identity.
7972 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7973 }
7974
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007975 return true;
7976 }
7977
7978 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007979 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7980 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981 skipCurrentReceiverLocked(app);
7982 }
7983
7984 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007985 for (BroadcastQueue queue : mBroadcastQueues) {
7986 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007987 }
7988 }
7989
Dan Egnor60d87622009-12-16 16:32:58 -08007990 /**
7991 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7992 * The application process will exit immediately after this call returns.
7993 * @param app object of the crashing app, null for the system server
7994 * @param crashInfo describing the exception
7995 */
7996 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007997 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007998 final String processName = app == null ? "system_server"
7999 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008000
8001 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008002 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008003 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008004 crashInfo.exceptionClassName,
8005 crashInfo.exceptionMessage,
8006 crashInfo.throwFileName,
8007 crashInfo.throwLineNumber);
8008
Jeff Sharkeya353d262011-10-28 11:12:06 -07008009 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008010
8011 crashApplication(r, crashInfo);
8012 }
8013
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008014 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008015 IBinder app,
8016 int violationMask,
8017 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008018 ProcessRecord r = findAppProcess(app, "StrictMode");
8019 if (r == null) {
8020 return;
8021 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008022
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008023 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008024 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008025 boolean logIt = true;
8026 synchronized (mAlreadyLoggedViolatedStacks) {
8027 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8028 logIt = false;
8029 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008030 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008031 // the relative pain numbers, without logging all
8032 // the stack traces repeatedly. We'd want to do
8033 // likewise in the client code, which also does
8034 // dup suppression, before the Binder call.
8035 } else {
8036 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8037 mAlreadyLoggedViolatedStacks.clear();
8038 }
8039 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8040 }
8041 }
8042 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008043 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008044 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008045 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008046
8047 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8048 AppErrorResult result = new AppErrorResult();
8049 synchronized (this) {
8050 final long origId = Binder.clearCallingIdentity();
8051
8052 Message msg = Message.obtain();
8053 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8054 HashMap<String, Object> data = new HashMap<String, Object>();
8055 data.put("result", result);
8056 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008057 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008058 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008059 msg.obj = data;
8060 mHandler.sendMessage(msg);
8061
8062 Binder.restoreCallingIdentity(origId);
8063 }
8064 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008065 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008066 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008067 }
8068
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008069 // Depending on the policy in effect, there could be a bunch of
8070 // these in quick succession so we try to batch these together to
8071 // minimize disk writes, number of dropbox entries, and maximize
8072 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008073 private void logStrictModeViolationToDropBox(
8074 ProcessRecord process,
8075 StrictMode.ViolationInfo info) {
8076 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008077 return;
8078 }
8079 final boolean isSystemApp = process == null ||
8080 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8081 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008082 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008083 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8084 final DropBoxManager dbox = (DropBoxManager)
8085 mContext.getSystemService(Context.DROPBOX_SERVICE);
8086
8087 // Exit early if the dropbox isn't configured to accept this report type.
8088 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8089
8090 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008091 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008092 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8093 synchronized (sb) {
8094 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008095 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008096 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8097 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008098 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8099 if (info.violationNumThisLoop != 0) {
8100 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8101 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008102 if (info.numAnimationsRunning != 0) {
8103 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8104 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008105 if (info.broadcastIntentAction != null) {
8106 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8107 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008108 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008109 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008110 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008111 if (info.numInstances != -1) {
8112 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8113 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008114 if (info.tags != null) {
8115 for (String tag : info.tags) {
8116 sb.append("Span-Tag: ").append(tag).append("\n");
8117 }
8118 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008119 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008120 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8121 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008122 }
8123 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008124
8125 // Only buffer up to ~64k. Various logging bits truncate
8126 // things at 128k.
8127 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008128 }
8129
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008130 // Flush immediately if the buffer's grown too large, or this
8131 // is a non-system app. Non-system apps are isolated with a
8132 // different tag & policy and not batched.
8133 //
8134 // Batching is useful during internal testing with
8135 // StrictMode settings turned up high. Without batching,
8136 // thousands of separate files could be created on boot.
8137 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008138 new Thread("Error dump: " + dropboxTag) {
8139 @Override
8140 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008141 String report;
8142 synchronized (sb) {
8143 report = sb.toString();
8144 sb.delete(0, sb.length());
8145 sb.trimToSize();
8146 }
8147 if (report.length() != 0) {
8148 dbox.addText(dropboxTag, report);
8149 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008150 }
8151 }.start();
8152 return;
8153 }
8154
8155 // System app batching:
8156 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008157 // An existing dropbox-writing thread is outstanding, so
8158 // we don't need to start it up. The existing thread will
8159 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008160 return;
8161 }
8162
8163 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8164 // (After this point, we shouldn't access AMS internal data structures.)
8165 new Thread("Error dump: " + dropboxTag) {
8166 @Override
8167 public void run() {
8168 // 5 second sleep to let stacks arrive and be batched together
8169 try {
8170 Thread.sleep(5000); // 5 seconds
8171 } catch (InterruptedException e) {}
8172
8173 String errorReport;
8174 synchronized (mStrictModeBuffer) {
8175 errorReport = mStrictModeBuffer.toString();
8176 if (errorReport.length() == 0) {
8177 return;
8178 }
8179 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8180 mStrictModeBuffer.trimToSize();
8181 }
8182 dbox.addText(dropboxTag, errorReport);
8183 }
8184 }.start();
8185 }
8186
Dan Egnor60d87622009-12-16 16:32:58 -08008187 /**
8188 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8189 * @param app object of the crashing app, null for the system server
8190 * @param tag reported by the caller
8191 * @param crashInfo describing the context of the error
8192 * @return true if the process should exit immediately (WTF is fatal)
8193 */
8194 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008195 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008196 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008197 final String processName = app == null ? "system_server"
8198 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008199
8200 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008201 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008202 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008203 tag, crashInfo.exceptionMessage);
8204
Jeff Sharkeya353d262011-10-28 11:12:06 -07008205 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008206
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008207 if (r != null && r.pid != Process.myPid() &&
8208 Settings.Secure.getInt(mContext.getContentResolver(),
8209 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008210 crashApplication(r, crashInfo);
8211 return true;
8212 } else {
8213 return false;
8214 }
8215 }
8216
8217 /**
8218 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8219 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8220 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008221 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008222 if (app == null) {
8223 return null;
8224 }
8225
8226 synchronized (this) {
8227 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8228 final int NA = apps.size();
8229 for (int ia=0; ia<NA; ia++) {
8230 ProcessRecord p = apps.valueAt(ia);
8231 if (p.thread != null && p.thread.asBinder() == app) {
8232 return p;
8233 }
8234 }
8235 }
8236
Dianne Hackborncb44d962011-03-10 17:02:27 -08008237 Slog.w(TAG, "Can't find mystery application for " + reason
8238 + " from pid=" + Binder.getCallingPid()
8239 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008240 return null;
8241 }
8242 }
8243
8244 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008245 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8246 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008247 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008248 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8249 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008250 // Watchdog thread ends up invoking this function (with
8251 // a null ProcessRecord) to add the stack file to dropbox.
8252 // Do not acquire a lock on this (am) in such cases, as it
8253 // could cause a potential deadlock, if and when watchdog
8254 // is invoked due to unavailability of lock on am and it
8255 // would prevent watchdog from killing system_server.
8256 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008257 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008258 return;
8259 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008260 // Note: ProcessRecord 'process' is guarded by the service
8261 // instance. (notably process.pkgList, which could otherwise change
8262 // concurrently during execution of this method)
8263 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008264 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008265 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008266 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008267 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8268 for (String pkg : process.pkgList) {
8269 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008270 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008271 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008272 if (pi != null) {
8273 sb.append(" v").append(pi.versionCode);
8274 if (pi.versionName != null) {
8275 sb.append(" (").append(pi.versionName).append(")");
8276 }
8277 }
8278 } catch (RemoteException e) {
8279 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008280 }
Dan Egnora455d192010-03-12 08:52:28 -08008281 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008282 }
Dan Egnora455d192010-03-12 08:52:28 -08008283 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008284 }
8285
8286 private static String processClass(ProcessRecord process) {
8287 if (process == null || process.pid == MY_PID) {
8288 return "system_server";
8289 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8290 return "system_app";
8291 } else {
8292 return "data_app";
8293 }
8294 }
8295
8296 /**
8297 * Write a description of an error (crash, WTF, ANR) to the drop box.
8298 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8299 * @param process which caused the error, null means the system server
8300 * @param activity which triggered the error, null if unknown
8301 * @param parent activity related to the error, null if unknown
8302 * @param subject line related to the error, null if absent
8303 * @param report in long form describing the error, null if absent
8304 * @param logFile to include in the report, null if none
8305 * @param crashInfo giving an application stack trace, null if absent
8306 */
8307 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008308 ProcessRecord process, String processName, ActivityRecord activity,
8309 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008310 final String report, final File logFile,
8311 final ApplicationErrorReport.CrashInfo crashInfo) {
8312 // NOTE -- this must never acquire the ActivityManagerService lock,
8313 // otherwise the watchdog may be prevented from resetting the system.
8314
8315 final String dropboxTag = processClass(process) + "_" + eventType;
8316 final DropBoxManager dbox = (DropBoxManager)
8317 mContext.getSystemService(Context.DROPBOX_SERVICE);
8318
8319 // Exit early if the dropbox isn't configured to accept this report type.
8320 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8321
8322 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008323 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008324 if (activity != null) {
8325 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8326 }
8327 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8328 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8329 }
8330 if (parent != null && parent != activity) {
8331 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8332 }
8333 if (subject != null) {
8334 sb.append("Subject: ").append(subject).append("\n");
8335 }
8336 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008337 if (Debug.isDebuggerConnected()) {
8338 sb.append("Debugger: Connected\n");
8339 }
Dan Egnora455d192010-03-12 08:52:28 -08008340 sb.append("\n");
8341
8342 // Do the rest in a worker thread to avoid blocking the caller on I/O
8343 // (After this point, we shouldn't access AMS internal data structures.)
8344 Thread worker = new Thread("Error dump: " + dropboxTag) {
8345 @Override
8346 public void run() {
8347 if (report != null) {
8348 sb.append(report);
8349 }
8350 if (logFile != null) {
8351 try {
8352 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8353 } catch (IOException e) {
8354 Slog.e(TAG, "Error reading " + logFile, e);
8355 }
8356 }
8357 if (crashInfo != null && crashInfo.stackTrace != null) {
8358 sb.append(crashInfo.stackTrace);
8359 }
8360
8361 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8362 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8363 if (lines > 0) {
8364 sb.append("\n");
8365
8366 // Merge several logcat streams, and take the last N lines
8367 InputStreamReader input = null;
8368 try {
8369 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8370 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8371 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8372
8373 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8374 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8375 input = new InputStreamReader(logcat.getInputStream());
8376
8377 int num;
8378 char[] buf = new char[8192];
8379 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8380 } catch (IOException e) {
8381 Slog.e(TAG, "Error running logcat", e);
8382 } finally {
8383 if (input != null) try { input.close(); } catch (IOException e) {}
8384 }
8385 }
8386
8387 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008388 }
Dan Egnora455d192010-03-12 08:52:28 -08008389 };
8390
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008391 if (process == null) {
8392 // If process is null, we are being called from some internal code
8393 // and may be about to die -- run this synchronously.
8394 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008395 } else {
8396 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008397 }
8398 }
8399
8400 /**
8401 * Bring up the "unexpected error" dialog box for a crashing app.
8402 * Deal with edge cases (intercepts from instrumented applications,
8403 * ActivityController, error intent receivers, that sort of thing).
8404 * @param r the application crashing
8405 * @param crashInfo describing the failure
8406 */
8407 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008408 long timeMillis = System.currentTimeMillis();
8409 String shortMsg = crashInfo.exceptionClassName;
8410 String longMsg = crashInfo.exceptionMessage;
8411 String stackTrace = crashInfo.stackTrace;
8412 if (shortMsg != null && longMsg != null) {
8413 longMsg = shortMsg + ": " + longMsg;
8414 } else if (shortMsg != null) {
8415 longMsg = shortMsg;
8416 }
8417
Dan Egnor60d87622009-12-16 16:32:58 -08008418 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008419 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008420 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008421 try {
8422 String name = r != null ? r.processName : null;
8423 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008424 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008425 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008426 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008427 + " at watcher's request");
8428 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008429 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008430 }
8431 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008432 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008433 }
8434 }
8435
8436 final long origId = Binder.clearCallingIdentity();
8437
8438 // If this process is running instrumentation, finish it.
8439 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008440 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008441 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008442 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8443 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008444 Bundle info = new Bundle();
8445 info.putString("shortMsg", shortMsg);
8446 info.putString("longMsg", longMsg);
8447 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8448 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008449 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008450 }
8451
Dan Egnor60d87622009-12-16 16:32:58 -08008452 // If we can't identify the process or it's already exceeded its crash quota,
8453 // quit right away without showing a crash dialog.
8454 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008455 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008456 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008457 }
8458
8459 Message msg = Message.obtain();
8460 msg.what = SHOW_ERROR_MSG;
8461 HashMap data = new HashMap();
8462 data.put("result", result);
8463 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008464 msg.obj = data;
8465 mHandler.sendMessage(msg);
8466
8467 Binder.restoreCallingIdentity(origId);
8468 }
8469
8470 int res = result.get();
8471
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008472 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008473 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008474 if (r != null && !r.isolated) {
8475 // XXX Can't keep track of crash time for isolated processes,
8476 // since they don't have a persistent identity.
8477 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008478 SystemClock.uptimeMillis());
8479 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008480 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008481 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008482 }
8483 }
8484
8485 if (appErrorIntent != null) {
8486 try {
8487 mContext.startActivity(appErrorIntent);
8488 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008489 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008490 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008492 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008493
8494 Intent createAppErrorIntentLocked(ProcessRecord r,
8495 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8496 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008497 if (report == null) {
8498 return null;
8499 }
8500 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8501 result.setComponent(r.errorReportReceiver);
8502 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8503 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8504 return result;
8505 }
8506
Dan Egnorb7f03672009-12-09 16:22:32 -08008507 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8508 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008509 if (r.errorReportReceiver == null) {
8510 return null;
8511 }
8512
8513 if (!r.crashing && !r.notResponding) {
8514 return null;
8515 }
8516
Dan Egnorb7f03672009-12-09 16:22:32 -08008517 ApplicationErrorReport report = new ApplicationErrorReport();
8518 report.packageName = r.info.packageName;
8519 report.installerPackageName = r.errorReportReceiver.getPackageName();
8520 report.processName = r.processName;
8521 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008522 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008523
Dan Egnorb7f03672009-12-09 16:22:32 -08008524 if (r.crashing) {
8525 report.type = ApplicationErrorReport.TYPE_CRASH;
8526 report.crashInfo = crashInfo;
8527 } else if (r.notResponding) {
8528 report.type = ApplicationErrorReport.TYPE_ANR;
8529 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008530
Dan Egnorb7f03672009-12-09 16:22:32 -08008531 report.anrInfo.activity = r.notRespondingReport.tag;
8532 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8533 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008534 }
8535
Dan Egnorb7f03672009-12-09 16:22:32 -08008536 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008537 }
8538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008539 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008540 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008541 // assume our apps are happy - lazy create the list
8542 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8543
Dianne Hackborn0c380492012-08-20 17:23:30 -07008544 final boolean allUsers = ActivityManager.checkUidPermission(
8545 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8546 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8547 int userId = UserHandle.getUserId(Binder.getCallingUid());
8548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008549 synchronized (this) {
8550
8551 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008552 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8553 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008554 if (!allUsers && app.userId != userId) {
8555 continue;
8556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008557 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8558 // This one's in trouble, so we'll generate a report for it
8559 // crashes are higher priority (in case there's a crash *and* an anr)
8560 ActivityManager.ProcessErrorStateInfo report = null;
8561 if (app.crashing) {
8562 report = app.crashingReport;
8563 } else if (app.notResponding) {
8564 report = app.notRespondingReport;
8565 }
8566
8567 if (report != null) {
8568 if (errList == null) {
8569 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8570 }
8571 errList.add(report);
8572 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008573 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 " crashing = " + app.crashing +
8575 " notResponding = " + app.notResponding);
8576 }
8577 }
8578 }
8579 }
8580
8581 return errList;
8582 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008583
8584 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008585 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008586 if (currApp != null) {
8587 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8588 }
8589 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008590 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8591 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008592 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8593 if (currApp != null) {
8594 currApp.lru = 0;
8595 }
8596 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008597 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008598 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8599 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8600 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8601 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8602 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8603 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8604 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8605 } else {
8606 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8607 }
8608 }
8609
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008610 private void fillInProcMemInfo(ProcessRecord app,
8611 ActivityManager.RunningAppProcessInfo outInfo) {
8612 outInfo.pid = app.pid;
8613 outInfo.uid = app.info.uid;
8614 if (mHeavyWeightProcess == app) {
8615 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8616 }
8617 if (app.persistent) {
8618 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8619 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008620 if (app.hasActivities) {
8621 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8622 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008623 outInfo.lastTrimLevel = app.trimMemoryLevel;
8624 int adj = app.curAdj;
8625 outInfo.importance = oomAdjToImportance(adj, outInfo);
8626 outInfo.importanceReasonCode = app.adjTypeCode;
8627 }
8628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008630 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008631 // Lazy instantiation of list
8632 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008633 final boolean allUsers = ActivityManager.checkUidPermission(
8634 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8635 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8636 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008637 synchronized (this) {
8638 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008639 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8640 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008641 if (!allUsers && app.userId != userId) {
8642 continue;
8643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8645 // Generate process state info for running application
8646 ActivityManager.RunningAppProcessInfo currApp =
8647 new ActivityManager.RunningAppProcessInfo(app.processName,
8648 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008649 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008650 if (app.adjSource instanceof ProcessRecord) {
8651 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008652 currApp.importanceReasonImportance = oomAdjToImportance(
8653 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008654 } else if (app.adjSource instanceof ActivityRecord) {
8655 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008656 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8657 }
8658 if (app.adjTarget instanceof ComponentName) {
8659 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8660 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008661 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008662 // + " lru=" + currApp.lru);
8663 if (runList == null) {
8664 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8665 }
8666 runList.add(currApp);
8667 }
8668 }
8669 }
8670 return runList;
8671 }
8672
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008673 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008674 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008675 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8676 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8677 if (runningApps != null && runningApps.size() > 0) {
8678 Set<String> extList = new HashSet<String>();
8679 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8680 if (app.pkgList != null) {
8681 for (String pkg : app.pkgList) {
8682 extList.add(pkg);
8683 }
8684 }
8685 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008686 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008687 for (String pkg : extList) {
8688 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008689 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008690 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8691 retList.add(info);
8692 }
8693 } catch (RemoteException e) {
8694 }
8695 }
8696 }
8697 return retList;
8698 }
8699
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008700 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008701 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8702 enforceNotIsolatedCaller("getMyMemoryState");
8703 synchronized (this) {
8704 ProcessRecord proc;
8705 synchronized (mPidsSelfLocked) {
8706 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8707 }
8708 fillInProcMemInfo(proc, outInfo);
8709 }
8710 }
8711
8712 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008713 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008714 if (checkCallingPermission(android.Manifest.permission.DUMP)
8715 != PackageManager.PERMISSION_GRANTED) {
8716 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8717 + Binder.getCallingPid()
8718 + ", uid=" + Binder.getCallingUid()
8719 + " without permission "
8720 + android.Manifest.permission.DUMP);
8721 return;
8722 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008723
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008724 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008725 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008726 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008727
8728 int opti = 0;
8729 while (opti < args.length) {
8730 String opt = args[opti];
8731 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8732 break;
8733 }
8734 opti++;
8735 if ("-a".equals(opt)) {
8736 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008737 } else if ("-c".equals(opt)) {
8738 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008739 } else if ("-h".equals(opt)) {
8740 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008741 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008742 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008743 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008744 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8745 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8746 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008747 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008748 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008749 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008750 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008751 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008752 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008753 pw.println(" all: dump all activities");
8754 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008755 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008756 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8757 pw.println(" a partial substring in a component name, a");
8758 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008759 pw.println(" -a: include all available server state.");
8760 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008761 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008762 } else {
8763 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008764 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008765 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008766
8767 long origId = Binder.clearCallingIdentity();
8768 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008769 // Is the caller requesting to dump a particular piece of data?
8770 if (opti < args.length) {
8771 String cmd = args[opti];
8772 opti++;
8773 if ("activities".equals(cmd) || "a".equals(cmd)) {
8774 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008775 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008777 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008778 String[] newArgs;
8779 String name;
8780 if (opti >= args.length) {
8781 name = null;
8782 newArgs = EMPTY_STRING_ARRAY;
8783 } else {
8784 name = args[opti];
8785 opti++;
8786 newArgs = new String[args.length - opti];
8787 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8788 args.length - opti);
8789 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008790 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008791 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008792 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008793 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008794 String[] newArgs;
8795 String name;
8796 if (opti >= args.length) {
8797 name = null;
8798 newArgs = EMPTY_STRING_ARRAY;
8799 } else {
8800 name = args[opti];
8801 opti++;
8802 newArgs = new String[args.length - opti];
8803 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8804 args.length - opti);
8805 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008806 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008807 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008808 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008809 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008810 String[] newArgs;
8811 String name;
8812 if (opti >= args.length) {
8813 name = null;
8814 newArgs = EMPTY_STRING_ARRAY;
8815 } else {
8816 name = args[opti];
8817 opti++;
8818 newArgs = new String[args.length - opti];
8819 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8820 args.length - opti);
8821 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008822 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008823 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008824 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008825 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8826 synchronized (this) {
8827 dumpOomLocked(fd, pw, args, opti, true);
8828 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008829 } else if ("provider".equals(cmd)) {
8830 String[] newArgs;
8831 String name;
8832 if (opti >= args.length) {
8833 name = null;
8834 newArgs = EMPTY_STRING_ARRAY;
8835 } else {
8836 name = args[opti];
8837 opti++;
8838 newArgs = new String[args.length - opti];
8839 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8840 }
8841 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8842 pw.println("No providers match: " + name);
8843 pw.println("Use -h for help.");
8844 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008845 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8846 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008847 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008848 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008849 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008850 String[] newArgs;
8851 String name;
8852 if (opti >= args.length) {
8853 name = null;
8854 newArgs = EMPTY_STRING_ARRAY;
8855 } else {
8856 name = args[opti];
8857 opti++;
8858 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008859 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8860 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008861 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008862 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008863 pw.println("No services match: " + name);
8864 pw.println("Use -h for help.");
8865 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008866 } else if ("package".equals(cmd)) {
8867 String[] newArgs;
8868 if (opti >= args.length) {
8869 pw.println("package: no package name specified");
8870 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008871 } else {
8872 dumpPackage = args[opti];
8873 opti++;
8874 newArgs = new String[args.length - opti];
8875 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8876 args.length - opti);
8877 args = newArgs;
8878 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008879 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008880 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008881 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8882 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008883 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008884 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008885 } else {
8886 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008887 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8888 pw.println("Bad activity command, or no activities match: " + cmd);
8889 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008890 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008891 }
8892 if (!more) {
8893 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008894 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008895 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008896 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008897
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008898 // No piece of data specified, dump everything.
8899 synchronized (this) {
8900 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008901 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008902 if (needSep) {
8903 pw.println(" ");
8904 }
8905 if (dumpAll) {
8906 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008907 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008908 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008909 if (needSep) {
8910 pw.println(" ");
8911 }
8912 if (dumpAll) {
8913 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008914 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008915 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008916 if (needSep) {
8917 pw.println(" ");
8918 }
8919 if (dumpAll) {
8920 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008921 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008922 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008923 if (needSep) {
8924 pw.println(" ");
8925 }
8926 if (dumpAll) {
8927 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008928 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008929 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008930 if (needSep) {
8931 pw.println(" ");
8932 }
8933 if (dumpAll) {
8934 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008935 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008936 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008937 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008938 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008939 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008940
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008941 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008942 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008943 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8944 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008945 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8946 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008947 pw.println(" ");
8948 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008949 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8950 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008951 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008953 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008954 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008955 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008956 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008957 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008958 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008959 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008960 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008961 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008962 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008963 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8964 pw.println(" ");
8965 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008966 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008967 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008968 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008969 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008970 pw.println(" ");
8971 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008972 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008973 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008975
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008976 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008977 if (mMainStack.mPausingActivity != null) {
8978 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008979 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008980 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008981 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008982 if (dumpAll) {
8983 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8984 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008985 pw.println(" mDismissKeyguardOnNextActivity: "
8986 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008988
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008989 if (mRecentTasks.size() > 0) {
8990 pw.println();
8991 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008992
8993 final int N = mRecentTasks.size();
8994 for (int i=0; i<N; i++) {
8995 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008996 if (dumpPackage != null) {
8997 if (tr.realActivity == null ||
8998 !dumpPackage.equals(tr.realActivity)) {
8999 continue;
9000 }
9001 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009002 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9003 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009004 if (dumpAll) {
9005 mRecentTasks.get(i).dump(pw, " ");
9006 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009007 }
9008 }
9009
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009010 if (dumpAll) {
9011 pw.println(" ");
9012 pw.println(" mCurTask: " + mCurTask);
9013 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009014
9015 return true;
9016 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009017
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009018 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009019 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009020 boolean needSep = false;
9021 int numPers = 0;
9022
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009023 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9024
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009025 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009026 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9027 final int NA = procs.size();
9028 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009029 ProcessRecord r = procs.valueAt(ia);
9030 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9031 continue;
9032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009033 if (!needSep) {
9034 pw.println(" All known processes:");
9035 needSep = true;
9036 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009037 pw.print(r.persistent ? " *PERS*" : " *APP*");
9038 pw.print(" UID "); pw.print(procs.keyAt(ia));
9039 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009040 r.dump(pw, " ");
9041 if (r.persistent) {
9042 numPers++;
9043 }
9044 }
9045 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009046 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009047
9048 if (mIsolatedProcesses.size() > 0) {
9049 if (needSep) pw.println(" ");
9050 needSep = true;
9051 pw.println(" Isolated process list (sorted by uid):");
9052 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9053 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9054 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9055 continue;
9056 }
9057 pw.println(String.format("%sIsolated #%2d: %s",
9058 " ", i, r.toString()));
9059 }
9060 }
9061
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009062 if (mLruProcesses.size() > 0) {
9063 if (needSep) pw.println(" ");
9064 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009065 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009066 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009067 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009068 needSep = true;
9069 }
9070
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009071 if (dumpAll) {
9072 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009073 boolean printed = false;
9074 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9075 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9076 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9077 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009078 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009079 if (!printed) {
9080 if (needSep) pw.println(" ");
9081 needSep = true;
9082 pw.println(" PID mappings:");
9083 printed = true;
9084 }
9085 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9086 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009087 }
9088 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009089 }
9090
9091 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009092 synchronized (mPidsSelfLocked) {
9093 boolean printed = false;
9094 for (int i=0; i<mForegroundProcesses.size(); i++) {
9095 ProcessRecord r = mPidsSelfLocked.get(
9096 mForegroundProcesses.valueAt(i).pid);
9097 if (dumpPackage != null && (r == null
9098 || !dumpPackage.equals(r.info.packageName))) {
9099 continue;
9100 }
9101 if (!printed) {
9102 if (needSep) pw.println(" ");
9103 needSep = true;
9104 pw.println(" Foreground Processes:");
9105 printed = true;
9106 }
9107 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9108 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009110 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009111 }
9112
9113 if (mPersistentStartingProcesses.size() > 0) {
9114 if (needSep) pw.println(" ");
9115 needSep = true;
9116 pw.println(" Persisent processes that are starting:");
9117 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009118 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009120
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009121 if (mRemovedProcesses.size() > 0) {
9122 if (needSep) pw.println(" ");
9123 needSep = true;
9124 pw.println(" Processes that are being removed:");
9125 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009126 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009127 }
9128
9129 if (mProcessesOnHold.size() > 0) {
9130 if (needSep) pw.println(" ");
9131 needSep = true;
9132 pw.println(" Processes that are on old until the system is ready:");
9133 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009134 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009136
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009137 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009138
9139 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009140 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009141 long now = SystemClock.uptimeMillis();
9142 for (Map.Entry<String, SparseArray<Long>> procs
9143 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009144 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009145 SparseArray<Long> uids = procs.getValue();
9146 final int N = uids.size();
9147 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009148 int puid = uids.keyAt(i);
9149 ProcessRecord r = mProcessNames.get(pname, puid);
9150 if (dumpPackage != null && (r == null
9151 || !dumpPackage.equals(r.info.packageName))) {
9152 continue;
9153 }
9154 if (!printed) {
9155 if (needSep) pw.println(" ");
9156 needSep = true;
9157 pw.println(" Time since processes crashed:");
9158 printed = true;
9159 }
9160 pw.print(" Process "); pw.print(pname);
9161 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009162 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009163 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9164 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009165 }
9166 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009167 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009168
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009169 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009170 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009171 for (Map.Entry<String, SparseArray<Long>> procs
9172 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009173 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009174 SparseArray<Long> uids = procs.getValue();
9175 final int N = uids.size();
9176 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009177 int puid = uids.keyAt(i);
9178 ProcessRecord r = mProcessNames.get(pname, puid);
9179 if (dumpPackage != null && (r == null
9180 || !dumpPackage.equals(r.info.packageName))) {
9181 continue;
9182 }
9183 if (!printed) {
9184 if (needSep) pw.println(" ");
9185 needSep = true;
9186 pw.println(" Bad processes:");
9187 }
9188 pw.print(" Bad process "); pw.print(pname);
9189 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009190 pw.print(": crashed at time ");
9191 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009192 }
9193 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009195
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009196 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009197 pw.println(" mStartedUsers:");
9198 for (int i=0; i<mStartedUsers.size(); i++) {
9199 UserStartedState uss = mStartedUsers.valueAt(i);
9200 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009201 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009202 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009203 pw.print(" mUserLru: [");
9204 for (int i=0; i<mUserLru.size(); i++) {
9205 if (i > 0) pw.print(", ");
9206 pw.print(mUserLru.get(i));
9207 }
9208 pw.println("]");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009209 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009210 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009211 if (dumpAll) {
9212 StringBuilder sb = new StringBuilder(128);
9213 sb.append(" mPreviousProcessVisibleTime: ");
9214 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9215 pw.println(sb);
9216 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009217 if (mHeavyWeightProcess != null) {
9218 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9219 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009220 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009221 if (dumpAll) {
9222 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009223 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009224 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009225 for (Map.Entry<String, Integer> entry
9226 : mCompatModePackages.getPackages().entrySet()) {
9227 String pkg = entry.getKey();
9228 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009229 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9230 continue;
9231 }
9232 if (!printed) {
9233 pw.println(" mScreenCompatPackages:");
9234 printed = true;
9235 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009236 pw.print(" "); pw.print(pkg); pw.print(": ");
9237 pw.print(mode); pw.println();
9238 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009239 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009240 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009241 if (mSleeping || mWentToSleep || mLockScreenShown) {
9242 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9243 + " mLockScreenShown " + mLockScreenShown);
9244 }
9245 if (mShuttingDown) {
9246 pw.println(" mShuttingDown=" + mShuttingDown);
9247 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009248 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9249 || mOrigWaitForDebugger) {
9250 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9251 + " mDebugTransient=" + mDebugTransient
9252 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9253 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009254 if (mOpenGlTraceApp != null) {
9255 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9256 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009257 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9258 || mProfileFd != null) {
9259 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9260 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9261 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9262 + mAutoStopProfiler);
9263 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009264 if (mAlwaysFinishActivities || mController != null) {
9265 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9266 + " mController=" + mController);
9267 }
9268 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009269 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009270 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009271 + " mProcessesReady=" + mProcessesReady
9272 + " mSystemReady=" + mSystemReady);
9273 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009274 + " mBooted=" + mBooted
9275 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009276 pw.print(" mLastPowerCheckRealtime=");
9277 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9278 pw.println("");
9279 pw.print(" mLastPowerCheckUptime=");
9280 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9281 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009282 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9283 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009284 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009285 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9286 + " mNumHiddenProcs=" + mNumHiddenProcs
9287 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009288 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009289 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009290
9291 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009292 }
9293
Dianne Hackborn287952c2010-09-22 22:34:31 -07009294 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009295 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009296 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009297 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009298 long now = SystemClock.uptimeMillis();
9299 for (int i=0; i<mProcessesToGc.size(); i++) {
9300 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009301 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9302 continue;
9303 }
9304 if (!printed) {
9305 if (needSep) pw.println(" ");
9306 needSep = true;
9307 pw.println(" Processes that are waiting to GC:");
9308 printed = true;
9309 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009310 pw.print(" Process "); pw.println(proc);
9311 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9312 pw.print(", last gced=");
9313 pw.print(now-proc.lastRequestedGc);
9314 pw.print(" ms ago, last lowMem=");
9315 pw.print(now-proc.lastLowMemory);
9316 pw.println(" ms ago");
9317
9318 }
9319 }
9320 return needSep;
9321 }
9322
9323 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9324 int opti, boolean dumpAll) {
9325 boolean needSep = false;
9326
9327 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009328 if (needSep) pw.println(" ");
9329 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009330 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009331 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009332 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009333 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9334 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9335 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9336 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9337 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009338 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009339 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009340 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009341 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009342 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009343 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009344
9345 if (needSep) pw.println(" ");
9346 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009347 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009348 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009349 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009350 needSep = true;
9351 }
9352
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009353 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009354
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009355 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009356 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009357 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009358 if (mHeavyWeightProcess != null) {
9359 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9360 }
9361
9362 return true;
9363 }
9364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009365 /**
9366 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009367 * - no provider specified: dump all the providers
9368 * - a flattened component name that matched an existing provider was specified as the
9369 * first arg: dump that one provider
9370 * - the first arg isn't the flattened component name of an existing provider:
9371 * dump all providers whose component contains the first arg as a substring
9372 */
9373 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9374 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009375 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009376 }
9377
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009378 static class ItemMatcher {
9379 ArrayList<ComponentName> components;
9380 ArrayList<String> strings;
9381 ArrayList<Integer> objects;
9382 boolean all;
9383
9384 ItemMatcher() {
9385 all = true;
9386 }
9387
9388 void build(String name) {
9389 ComponentName componentName = ComponentName.unflattenFromString(name);
9390 if (componentName != null) {
9391 if (components == null) {
9392 components = new ArrayList<ComponentName>();
9393 }
9394 components.add(componentName);
9395 all = false;
9396 } else {
9397 int objectId = 0;
9398 // Not a '/' separated full component name; maybe an object ID?
9399 try {
9400 objectId = Integer.parseInt(name, 16);
9401 if (objects == null) {
9402 objects = new ArrayList<Integer>();
9403 }
9404 objects.add(objectId);
9405 all = false;
9406 } catch (RuntimeException e) {
9407 // Not an integer; just do string match.
9408 if (strings == null) {
9409 strings = new ArrayList<String>();
9410 }
9411 strings.add(name);
9412 all = false;
9413 }
9414 }
9415 }
9416
9417 int build(String[] args, int opti) {
9418 for (; opti<args.length; opti++) {
9419 String name = args[opti];
9420 if ("--".equals(name)) {
9421 return opti+1;
9422 }
9423 build(name);
9424 }
9425 return opti;
9426 }
9427
9428 boolean match(Object object, ComponentName comp) {
9429 if (all) {
9430 return true;
9431 }
9432 if (components != null) {
9433 for (int i=0; i<components.size(); i++) {
9434 if (components.get(i).equals(comp)) {
9435 return true;
9436 }
9437 }
9438 }
9439 if (objects != null) {
9440 for (int i=0; i<objects.size(); i++) {
9441 if (System.identityHashCode(object) == objects.get(i)) {
9442 return true;
9443 }
9444 }
9445 }
9446 if (strings != null) {
9447 String flat = comp.flattenToString();
9448 for (int i=0; i<strings.size(); i++) {
9449 if (flat.contains(strings.get(i))) {
9450 return true;
9451 }
9452 }
9453 }
9454 return false;
9455 }
9456 }
9457
Dianne Hackborn625ac272010-09-17 18:29:22 -07009458 /**
9459 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009460 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009461 * - the cmd arg isn't the flattened component name of an existing activity:
9462 * dump all activity whose component contains the cmd as a substring
9463 * - A hex number of the ActivityRecord object instance.
9464 */
9465 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9466 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009467 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009468
9469 if ("all".equals(name)) {
9470 synchronized (this) {
9471 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009472 activities.add(r1);
9473 }
9474 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009475 } else if ("top".equals(name)) {
9476 synchronized (this) {
9477 final int N = mMainStack.mHistory.size();
9478 if (N > 0) {
9479 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9480 }
9481 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009482 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009483 ItemMatcher matcher = new ItemMatcher();
9484 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009485
9486 synchronized (this) {
9487 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009488 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009489 activities.add(r1);
9490 }
9491 }
9492 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009493 }
9494
9495 if (activities.size() <= 0) {
9496 return false;
9497 }
9498
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009499 String[] newArgs = new String[args.length - opti];
9500 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9501
Dianne Hackborn30d71892010-12-11 10:37:55 -08009502 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009503 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009504 for (int i=activities.size()-1; i>=0; i--) {
9505 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009506 if (needSep) {
9507 pw.println();
9508 }
9509 needSep = true;
9510 synchronized (this) {
9511 if (lastTask != r.task) {
9512 lastTask = r.task;
9513 pw.print("TASK "); pw.print(lastTask.affinity);
9514 pw.print(" id="); pw.println(lastTask.taskId);
9515 if (dumpAll) {
9516 lastTask.dump(pw, " ");
9517 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009518 }
9519 }
9520 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009521 }
9522 return true;
9523 }
9524
9525 /**
9526 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9527 * there is a thread associated with the activity.
9528 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009529 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009530 final ActivityRecord r, String[] args, boolean dumpAll) {
9531 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009532 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009533 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9534 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9535 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009536 if (r.app != null) pw.println(r.app.pid);
9537 else pw.println("(not running)");
9538 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009539 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009540 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009541 }
9542 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009543 // flush anything that is already in the PrintWriter since the thread is going
9544 // to write to the file descriptor directly
9545 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009546 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009547 TransferPipe tp = new TransferPipe();
9548 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009549 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9550 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009551 tp.go(fd);
9552 } finally {
9553 tp.kill();
9554 }
9555 } catch (IOException e) {
9556 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009557 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009558 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009559 }
9560 }
9561 }
9562
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009563 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009564 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009565 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009566 boolean onlyHistory = false;
9567
9568 if ("history".equals(dumpPackage)) {
9569 onlyHistory = true;
9570 dumpPackage = null;
9571 }
9572
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009573 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009574 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009575 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009576 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009577 Iterator it = mRegisteredReceivers.values().iterator();
9578 while (it.hasNext()) {
9579 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009580 if (dumpPackage != null && (r.app == null ||
9581 !dumpPackage.equals(r.app.info.packageName))) {
9582 continue;
9583 }
9584 if (!printed) {
9585 pw.println(" Registered Receivers:");
9586 needSep = true;
9587 printed = true;
9588 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009589 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009590 r.dump(pw, " ");
9591 }
9592 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009593
9594 if (mReceiverResolver.dump(pw, needSep ?
9595 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9596 " ", dumpPackage, false)) {
9597 needSep = true;
9598 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009599 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009600
9601 for (BroadcastQueue q : mBroadcastQueues) {
9602 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009604
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009605 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009606
Dianne Hackborn786b4402012-08-27 15:14:02 -07009607 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009608 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9609 if (needSep) {
9610 pw.println();
9611 }
9612 needSep = true;
9613 pw.print(" Sticky broadcasts for user ");
9614 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9615 StringBuilder sb = new StringBuilder(128);
9616 for (Map.Entry<String, ArrayList<Intent>> ent
9617 : mStickyBroadcasts.valueAt(user).entrySet()) {
9618 pw.print(" * Sticky action "); pw.print(ent.getKey());
9619 if (dumpAll) {
9620 pw.println(":");
9621 ArrayList<Intent> intents = ent.getValue();
9622 final int N = intents.size();
9623 for (int i=0; i<N; i++) {
9624 sb.setLength(0);
9625 sb.append(" Intent: ");
9626 intents.get(i).toShortString(sb, false, true, false, false);
9627 pw.println(sb.toString());
9628 Bundle bundle = intents.get(i).getExtras();
9629 if (bundle != null) {
9630 pw.print(" ");
9631 pw.println(bundle.toString());
9632 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009633 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009634 } else {
9635 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009636 }
9637 }
9638 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009639 }
9640
Dianne Hackborn786b4402012-08-27 15:14:02 -07009641 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009642 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009643 for (BroadcastQueue queue : mBroadcastQueues) {
9644 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9645 + queue.mBroadcastsScheduled);
9646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009647 pw.println(" mHandler:");
9648 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009649 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009650 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009651
9652 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009653 }
9654
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009655 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009656 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009657 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009658
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009659 ItemMatcher matcher = new ItemMatcher();
9660 matcher.build(args, opti);
9661
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009662 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009663
9664 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009665
9666 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009667 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009668 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009669 ContentProviderRecord r = mLaunchingProviders.get(i);
9670 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9671 continue;
9672 }
9673 if (!printed) {
9674 if (needSep) pw.println(" ");
9675 needSep = true;
9676 pw.println(" Launching content providers:");
9677 printed = true;
9678 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009679 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009680 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009681 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009682 }
9683
9684 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009685 if (needSep) pw.println();
9686 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009687 pw.println("Granted Uri Permissions:");
9688 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9689 int uid = mGrantedUriPermissions.keyAt(i);
9690 HashMap<Uri, UriPermission> perms
9691 = mGrantedUriPermissions.valueAt(i);
9692 pw.print(" * UID "); pw.print(uid);
9693 pw.println(" holds:");
9694 for (UriPermission perm : perms.values()) {
9695 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009696 if (dumpAll) {
9697 perm.dump(pw, " ");
9698 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009699 }
9700 }
9701 needSep = true;
9702 }
9703
9704 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009705 }
9706
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009707 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009708 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009709 boolean needSep = false;
9710
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009711 if (mIntentSenderRecords.size() > 0) {
9712 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009713 Iterator<WeakReference<PendingIntentRecord>> it
9714 = mIntentSenderRecords.values().iterator();
9715 while (it.hasNext()) {
9716 WeakReference<PendingIntentRecord> ref = it.next();
9717 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009718 if (dumpPackage != null && (rec == null
9719 || !dumpPackage.equals(rec.key.packageName))) {
9720 continue;
9721 }
9722 if (!printed) {
9723 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9724 printed = true;
9725 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009726 needSep = true;
9727 if (rec != null) {
9728 pw.print(" * "); pw.println(rec);
9729 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009730 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009731 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009732 } else {
9733 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009734 }
9735 }
9736 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009737
9738 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009739 }
9740
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009741 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009742 String prefix, String label, boolean complete, boolean brief, boolean client,
9743 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009744 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009745 boolean needNL = false;
9746 final String innerPrefix = prefix + " ";
9747 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009748 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009749 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009750 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9751 continue;
9752 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009753 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009754 if (needNL) {
9755 pw.println(" ");
9756 needNL = false;
9757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009758 if (lastTask != r.task) {
9759 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009760 pw.print(prefix);
9761 pw.print(full ? "* " : " ");
9762 pw.println(lastTask);
9763 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009764 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009765 } else if (complete) {
9766 // Complete + brief == give a summary. Isn't that obvious?!?
9767 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009768 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009769 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009770 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009772 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009773 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9774 pw.print(" #"); pw.print(i); pw.print(": ");
9775 pw.println(r);
9776 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009777 r.dump(pw, innerPrefix);
9778 } else if (complete) {
9779 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009780 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009781 if (r.app != null) {
9782 pw.print(innerPrefix); pw.println(r.app);
9783 }
9784 }
9785 if (client && r.app != null && r.app.thread != null) {
9786 // flush anything that is already in the PrintWriter since the thread is going
9787 // to write to the file descriptor directly
9788 pw.flush();
9789 try {
9790 TransferPipe tp = new TransferPipe();
9791 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009792 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9793 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009794 // Short timeout, since blocking here can
9795 // deadlock with the application.
9796 tp.go(fd, 2000);
9797 } finally {
9798 tp.kill();
9799 }
9800 } catch (IOException e) {
9801 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9802 } catch (RemoteException e) {
9803 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9804 }
9805 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009807 }
9808 }
9809
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009810 private static String buildOomTag(String prefix, String space, int val, int base) {
9811 if (val == base) {
9812 if (space == null) return prefix;
9813 return prefix + " ";
9814 }
9815 return prefix + "+" + Integer.toString(val-base);
9816 }
9817
9818 private static final int dumpProcessList(PrintWriter pw,
9819 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009820 String prefix, String normalLabel, String persistentLabel,
9821 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009822 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009823 final int N = list.size()-1;
9824 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009825 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009826 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9827 continue;
9828 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009829 pw.println(String.format("%s%s #%2d: %s",
9830 prefix, (r.persistent ? persistentLabel : normalLabel),
9831 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009832 if (r.persistent) {
9833 numPers++;
9834 }
9835 }
9836 return numPers;
9837 }
9838
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009839 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009840 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009841 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009842 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009843
Dianne Hackborn905577f2011-09-07 18:31:28 -07009844 ArrayList<Pair<ProcessRecord, Integer>> list
9845 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9846 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009847 ProcessRecord r = origList.get(i);
9848 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9849 continue;
9850 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009851 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9852 }
9853
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009854 if (list.size() <= 0) {
9855 return false;
9856 }
9857
Dianne Hackborn905577f2011-09-07 18:31:28 -07009858 Comparator<Pair<ProcessRecord, Integer>> comparator
9859 = new Comparator<Pair<ProcessRecord, Integer>>() {
9860 @Override
9861 public int compare(Pair<ProcessRecord, Integer> object1,
9862 Pair<ProcessRecord, Integer> object2) {
9863 if (object1.first.setAdj != object2.first.setAdj) {
9864 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9865 }
9866 if (object1.second.intValue() != object2.second.intValue()) {
9867 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9868 }
9869 return 0;
9870 }
9871 };
9872
9873 Collections.sort(list, comparator);
9874
Dianne Hackborn287952c2010-09-22 22:34:31 -07009875 final long curRealtime = SystemClock.elapsedRealtime();
9876 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9877 final long curUptime = SystemClock.uptimeMillis();
9878 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9879
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009880 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009881 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009882 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009883 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009884 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009885 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9886 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009887 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9888 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009889 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9890 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009891 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9892 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009893 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009894 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009895 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9896 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9897 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9898 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9899 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9900 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9901 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9902 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009903 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9904 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009905 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9906 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009907 } else {
9908 oomAdj = Integer.toString(r.setAdj);
9909 }
9910 String schedGroup;
9911 switch (r.setSchedGroup) {
9912 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9913 schedGroup = "B";
9914 break;
9915 case Process.THREAD_GROUP_DEFAULT:
9916 schedGroup = "F";
9917 break;
9918 default:
9919 schedGroup = Integer.toString(r.setSchedGroup);
9920 break;
9921 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009922 String foreground;
9923 if (r.foregroundActivities) {
9924 foreground = "A";
9925 } else if (r.foregroundServices) {
9926 foreground = "S";
9927 } else {
9928 foreground = " ";
9929 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009930 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009931 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009932 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9933 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009934 if (r.adjSource != null || r.adjTarget != null) {
9935 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009936 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009937 if (r.adjTarget instanceof ComponentName) {
9938 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9939 } else if (r.adjTarget != null) {
9940 pw.print(r.adjTarget.toString());
9941 } else {
9942 pw.print("{null}");
9943 }
9944 pw.print("<=");
9945 if (r.adjSource instanceof ProcessRecord) {
9946 pw.print("Proc{");
9947 pw.print(((ProcessRecord)r.adjSource).toShortString());
9948 pw.println("}");
9949 } else if (r.adjSource != null) {
9950 pw.println(r.adjSource.toString());
9951 } else {
9952 pw.println("{null}");
9953 }
9954 }
9955 if (inclDetails) {
9956 pw.print(prefix);
9957 pw.print(" ");
9958 pw.print("oom: max="); pw.print(r.maxAdj);
9959 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009960 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009961 pw.print(" curRaw="); pw.print(r.curRawAdj);
9962 pw.print(" setRaw="); pw.print(r.setRawAdj);
9963 pw.print(" cur="); pw.print(r.curAdj);
9964 pw.print(" set="); pw.println(r.setAdj);
9965 pw.print(prefix);
9966 pw.print(" ");
9967 pw.print("keeping="); pw.print(r.keeping);
9968 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009969 pw.print(" empty="); pw.print(r.empty);
9970 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009971
9972 if (!r.keeping) {
9973 if (r.lastWakeTime != 0) {
9974 long wtime;
9975 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9976 synchronized (stats) {
9977 wtime = stats.getProcessWakeTime(r.info.uid,
9978 r.pid, curRealtime);
9979 }
9980 long timeUsed = wtime - r.lastWakeTime;
9981 pw.print(prefix);
9982 pw.print(" ");
9983 pw.print("keep awake over ");
9984 TimeUtils.formatDuration(realtimeSince, pw);
9985 pw.print(" used ");
9986 TimeUtils.formatDuration(timeUsed, pw);
9987 pw.print(" (");
9988 pw.print((timeUsed*100)/realtimeSince);
9989 pw.println("%)");
9990 }
9991 if (r.lastCpuTime != 0) {
9992 long timeUsed = r.curCpuTime - r.lastCpuTime;
9993 pw.print(prefix);
9994 pw.print(" ");
9995 pw.print("run cpu over ");
9996 TimeUtils.formatDuration(uptimeSince, pw);
9997 pw.print(" used ");
9998 TimeUtils.formatDuration(timeUsed, pw);
9999 pw.print(" (");
10000 pw.print((timeUsed*100)/uptimeSince);
10001 pw.println("%)");
10002 }
10003 }
10004 }
10005 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010006 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010007 }
10008
Dianne Hackbornb437e092011-08-05 17:50:29 -070010009 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010010 ArrayList<ProcessRecord> procs;
10011 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010012 if (args != null && args.length > start
10013 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010014 procs = new ArrayList<ProcessRecord>();
10015 int pid = -1;
10016 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010017 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010018 } catch (NumberFormatException e) {
10019
10020 }
10021 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10022 ProcessRecord proc = mLruProcesses.get(i);
10023 if (proc.pid == pid) {
10024 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010025 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010026 procs.add(proc);
10027 }
10028 }
10029 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010030 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010031 return null;
10032 }
10033 } else {
10034 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10035 }
10036 }
10037 return procs;
10038 }
10039
10040 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10041 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010042 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010043 if (procs == null) {
10044 return;
10045 }
10046
10047 long uptime = SystemClock.uptimeMillis();
10048 long realtime = SystemClock.elapsedRealtime();
10049 pw.println("Applications Graphics Acceleration Info:");
10050 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10051
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010052 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10053 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010054 if (r.thread != null) {
10055 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10056 pw.flush();
10057 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010058 TransferPipe tp = new TransferPipe();
10059 try {
10060 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10061 tp.go(fd);
10062 } finally {
10063 tp.kill();
10064 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010065 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010066 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010067 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010068 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010069 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010070 pw.flush();
10071 }
10072 }
10073 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010074 }
10075
Jeff Brown6754ba22011-12-14 20:20:01 -080010076 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10077 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10078 if (procs == null) {
10079 return;
10080 }
10081
10082 pw.println("Applications Database Info:");
10083
10084 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10085 ProcessRecord r = procs.get(i);
10086 if (r.thread != null) {
10087 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10088 pw.flush();
10089 try {
10090 TransferPipe tp = new TransferPipe();
10091 try {
10092 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10093 tp.go(fd);
10094 } finally {
10095 tp.kill();
10096 }
10097 } catch (IOException e) {
10098 pw.println("Failure while dumping the app: " + r);
10099 pw.flush();
10100 } catch (RemoteException e) {
10101 pw.println("Got a RemoteException while dumping the app " + r);
10102 pw.flush();
10103 }
10104 }
10105 }
10106 }
10107
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010108 final static class MemItem {
10109 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010110 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010111 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010112 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010113 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010114
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010115 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010116 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010117 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010118 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010119 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010120 }
10121 }
10122
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010123 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010124 boolean sort) {
10125 if (sort) {
10126 Collections.sort(items, new Comparator<MemItem>() {
10127 @Override
10128 public int compare(MemItem lhs, MemItem rhs) {
10129 if (lhs.pss < rhs.pss) {
10130 return 1;
10131 } else if (lhs.pss > rhs.pss) {
10132 return -1;
10133 }
10134 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010135 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010136 });
10137 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010138
10139 for (int i=0; i<items.size(); i++) {
10140 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010141 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010142 if (mi.subitems != null) {
10143 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10144 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010145 }
10146 }
10147
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010148 // These are in KB.
10149 static final long[] DUMP_MEM_BUCKETS = new long[] {
10150 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10151 120*1024, 160*1024, 200*1024,
10152 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10153 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10154 };
10155
Dianne Hackborn672342c2011-11-29 11:29:02 -080010156 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10157 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010158 int start = label.lastIndexOf('.');
10159 if (start >= 0) start++;
10160 else start = 0;
10161 int end = label.length();
10162 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10163 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10164 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10165 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010166 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010167 out.append(label, start, end);
10168 return;
10169 }
10170 }
10171 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010172 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010173 out.append(label, start, end);
10174 }
10175
10176 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10177 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10178 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10179 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10180 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10181 };
10182 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10183 "System", "Persistent", "Foreground",
10184 "Visible", "Perceptible", "Heavy Weight",
10185 "Backup", "A Services", "Home", "Previous",
10186 "B Services", "Background"
10187 };
10188
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010189 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010190 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010191 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010192 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010193 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010194
10195 int opti = 0;
10196 while (opti < args.length) {
10197 String opt = args[opti];
10198 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10199 break;
10200 }
10201 opti++;
10202 if ("-a".equals(opt)) {
10203 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010204 } else if ("--oom".equals(opt)) {
10205 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010206 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010207 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010208 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010209 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010210 pw.println("If [process] is specified it can be the name or ");
10211 pw.println("pid of a specific process to dump.");
10212 return;
10213 } else {
10214 pw.println("Unknown argument: " + opt + "; use -h for help");
10215 }
10216 }
10217
10218 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010219 if (procs == null) {
10220 return;
10221 }
10222
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010223 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010224 long uptime = SystemClock.uptimeMillis();
10225 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010226
10227 if (procs.size() == 1 || isCheckinRequest) {
10228 dumpAll = true;
10229 }
10230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010231 if (isCheckinRequest) {
10232 // short checkin version
10233 pw.println(uptime + "," + realtime);
10234 pw.flush();
10235 } else {
10236 pw.println("Applications Memory Usage (kB):");
10237 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10238 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010239
Dianne Hackbornb437e092011-08-05 17:50:29 -070010240 String[] innerArgs = new String[args.length-opti];
10241 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10242
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010243 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10244 long nativePss=0, dalvikPss=0, otherPss=0;
10245 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10246
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010247 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10248 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10249 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010250
10251 long totalPss = 0;
10252
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010253 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10254 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010255 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010256 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010257 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10258 pw.flush();
10259 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010260 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010261 if (dumpAll) {
10262 try {
10263 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10264 } catch (RemoteException e) {
10265 if (!isCheckinRequest) {
10266 pw.println("Got RemoteException!");
10267 pw.flush();
10268 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010269 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010270 } else {
10271 mi = new Debug.MemoryInfo();
10272 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010273 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010274
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010275 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010276 long myTotalPss = mi.getTotalPss();
10277 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010278 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010279 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010280 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010281
10282 nativePss += mi.nativePss;
10283 dalvikPss += mi.dalvikPss;
10284 otherPss += mi.otherPss;
10285 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10286 long mem = mi.getOtherPss(j);
10287 miscPss[j] += mem;
10288 otherPss -= mem;
10289 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010290
10291 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010292 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10293 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010294 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010295 if (oomProcs[oomIndex] == null) {
10296 oomProcs[oomIndex] = new ArrayList<MemItem>();
10297 }
10298 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010299 break;
10300 }
10301 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010303 }
10304 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010305
10306 if (!isCheckinRequest && procs.size() > 1) {
10307 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10308
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010309 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10310 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10311 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010312 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010313 String label = Debug.MemoryInfo.getOtherLabel(j);
10314 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010315 }
10316
Dianne Hackbornb437e092011-08-05 17:50:29 -070010317 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10318 for (int j=0; j<oomPss.length; j++) {
10319 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010320 String label = DUMP_MEM_OOM_LABEL[j];
10321 MemItem item = new MemItem(label, label, oomPss[j],
10322 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010323 item.subitems = oomProcs[j];
10324 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010325 }
10326 }
10327
Dianne Hackborn672342c2011-11-29 11:29:02 -080010328 if (outTag != null || outStack != null) {
10329 if (outTag != null) {
10330 appendMemBucket(outTag, totalPss, "total", false);
10331 }
10332 if (outStack != null) {
10333 appendMemBucket(outStack, totalPss, "total", true);
10334 }
10335 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010336 for (int i=0; i<oomMems.size(); i++) {
10337 MemItem miCat = oomMems.get(i);
10338 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10339 continue;
10340 }
10341 if (miCat.id < ProcessList.SERVICE_ADJ
10342 || miCat.id == ProcessList.HOME_APP_ADJ
10343 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010344 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10345 outTag.append(" / ");
10346 }
10347 if (outStack != null) {
10348 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10349 if (firstLine) {
10350 outStack.append(":");
10351 firstLine = false;
10352 }
10353 outStack.append("\n\t at ");
10354 } else {
10355 outStack.append("$");
10356 }
10357 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010358 for (int j=0; j<miCat.subitems.size(); j++) {
10359 MemItem mi = miCat.subitems.get(j);
10360 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010361 if (outTag != null) {
10362 outTag.append(" ");
10363 }
10364 if (outStack != null) {
10365 outStack.append("$");
10366 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010367 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010368 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10369 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10370 }
10371 if (outStack != null) {
10372 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10373 }
10374 }
10375 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10376 outStack.append("(");
10377 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10378 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10379 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10380 outStack.append(":");
10381 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10382 }
10383 }
10384 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010385 }
10386 }
10387 }
10388 }
10389
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010390 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010391 pw.println();
10392 pw.println("Total PSS by process:");
10393 dumpMemItems(pw, " ", procMems, true);
10394 pw.println();
10395 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010396 pw.println("Total PSS by OOM adjustment:");
10397 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010398 if (!oomOnly) {
10399 PrintWriter out = categoryPw != null ? categoryPw : pw;
10400 out.println();
10401 out.println("Total PSS by category:");
10402 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010403 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010404 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010405 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010406 final int[] SINGLE_LONG_FORMAT = new int[] {
10407 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10408 };
10409 long[] longOut = new long[1];
10410 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10411 SINGLE_LONG_FORMAT, null, longOut, null);
10412 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10413 longOut[0] = 0;
10414 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10415 SINGLE_LONG_FORMAT, null, longOut, null);
10416 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10417 longOut[0] = 0;
10418 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10419 SINGLE_LONG_FORMAT, null, longOut, null);
10420 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10421 longOut[0] = 0;
10422 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10423 SINGLE_LONG_FORMAT, null, longOut, null);
10424 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10425 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10426 pw.print(shared); pw.println(" kB");
10427 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10428 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010430 }
10431
10432 /**
10433 * Searches array of arguments for the specified string
10434 * @param args array of argument strings
10435 * @param value value to search for
10436 * @return true if the value is contained in the array
10437 */
10438 private static boolean scanArgs(String[] args, String value) {
10439 if (args != null) {
10440 for (String arg : args) {
10441 if (value.equals(arg)) {
10442 return true;
10443 }
10444 }
10445 }
10446 return false;
10447 }
10448
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010449 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10450 ContentProviderRecord cpr, boolean always) {
10451 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10452
10453 if (!inLaunching || always) {
10454 synchronized (cpr) {
10455 cpr.launchingApp = null;
10456 cpr.notifyAll();
10457 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010458 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010459 String names[] = cpr.info.authority.split(";");
10460 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010461 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010462 }
10463 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010464
10465 for (int i=0; i<cpr.connections.size(); i++) {
10466 ContentProviderConnection conn = cpr.connections.get(i);
10467 if (conn.waiting) {
10468 // If this connection is waiting for the provider, then we don't
10469 // need to mess with its process unless we are always removing
10470 // or for some reason the provider is not currently launching.
10471 if (inLaunching && !always) {
10472 continue;
10473 }
10474 }
10475 ProcessRecord capp = conn.client;
10476 conn.dead = true;
10477 if (conn.stableCount > 0) {
10478 if (!capp.persistent && capp.thread != null
10479 && capp.pid != 0
10480 && capp.pid != MY_PID) {
10481 Slog.i(TAG, "Kill " + capp.processName
10482 + " (pid " + capp.pid + "): provider " + cpr.info.name
10483 + " in dying process " + (proc != null ? proc.processName : "??"));
10484 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10485 capp.processName, capp.setAdj, "dying provider "
10486 + cpr.name.toShortString());
10487 Process.killProcessQuiet(capp.pid);
10488 }
10489 } else if (capp.thread != null && conn.provider.provider != null) {
10490 try {
10491 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10492 } catch (RemoteException e) {
10493 }
10494 // In the protocol here, we don't expect the client to correctly
10495 // clean up this connection, we'll just remove it.
10496 cpr.connections.remove(i);
10497 conn.client.conProviders.remove(conn);
10498 }
10499 }
10500
10501 if (inLaunching && always) {
10502 mLaunchingProviders.remove(cpr);
10503 }
10504 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010505 }
10506
10507 /**
10508 * Main code for cleaning up a process when it has gone away. This is
10509 * called both as a result of the process dying, or directly when stopping
10510 * a process when running in single process mode.
10511 */
10512 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010513 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010514 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010515 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010516 }
10517
Dianne Hackborn36124872009-10-08 16:22:03 -070010518 mProcessesToGc.remove(app);
10519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010520 // Dismiss any open dialogs.
10521 if (app.crashDialog != null) {
10522 app.crashDialog.dismiss();
10523 app.crashDialog = null;
10524 }
10525 if (app.anrDialog != null) {
10526 app.anrDialog.dismiss();
10527 app.anrDialog = null;
10528 }
10529 if (app.waitDialog != null) {
10530 app.waitDialog.dismiss();
10531 app.waitDialog = null;
10532 }
10533
10534 app.crashing = false;
10535 app.notResponding = false;
10536
10537 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010538 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010539 app.thread = null;
10540 app.forcingToForeground = null;
10541 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010542 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010543 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010544 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010545
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010546 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010547
10548 boolean restart = false;
10549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010550 // Remove published content providers.
10551 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010552 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010553 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010554 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010555
10556 final boolean always = app.bad || !allowRestart;
10557 if (removeDyingProviderLocked(app, cpr, always) || always) {
10558 // We left the provider in the launching list, need to
10559 // restart it.
10560 restart = true;
10561 }
10562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010563 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010564 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010565 }
10566 app.pubProviders.clear();
10567 }
10568
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010569 // Take care of any launching providers waiting for this process.
10570 if (checkAppInLaunchingProvidersLocked(app, false)) {
10571 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010572 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010574 // Unregister from connected content providers.
10575 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010576 for (int i=0; i<app.conProviders.size(); i++) {
10577 ContentProviderConnection conn = app.conProviders.get(i);
10578 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010579 }
10580 app.conProviders.clear();
10581 }
10582
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010583 // At this point there may be remaining entries in mLaunchingProviders
10584 // where we were the only one waiting, so they are no longer of use.
10585 // Look for these and clean up if found.
10586 // XXX Commented out for now. Trying to figure out a way to reproduce
10587 // the actual situation to identify what is actually going on.
10588 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010589 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010590 ContentProviderRecord cpr = (ContentProviderRecord)
10591 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010592 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010593 synchronized (cpr) {
10594 cpr.launchingApp = null;
10595 cpr.notifyAll();
10596 }
10597 }
10598 }
10599 }
10600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010601 skipCurrentReceiverLocked(app);
10602
10603 // Unregister any receivers.
10604 if (app.receivers.size() > 0) {
10605 Iterator<ReceiverList> it = app.receivers.iterator();
10606 while (it.hasNext()) {
10607 removeReceiverLocked(it.next());
10608 }
10609 app.receivers.clear();
10610 }
10611
Christopher Tate181fafa2009-05-14 11:12:14 -070010612 // If the app is undergoing backup, tell the backup manager about it
10613 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010614 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010615 try {
10616 IBackupManager bm = IBackupManager.Stub.asInterface(
10617 ServiceManager.getService(Context.BACKUP_SERVICE));
10618 bm.agentDisconnected(app.info.packageName);
10619 } catch (RemoteException e) {
10620 // can't happen; backup manager is local
10621 }
10622 }
10623
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010624 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10625 ProcessChangeItem item = mPendingProcessChanges.get(i);
10626 if (item.pid == app.pid) {
10627 mPendingProcessChanges.remove(i);
10628 mAvailProcessChanges.add(item);
10629 }
10630 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010631 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010633 // If the caller is restarting this app, then leave it in its
10634 // current lists and let the caller take care of it.
10635 if (restarting) {
10636 return;
10637 }
10638
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010639 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010640 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010641 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010642 mProcessNames.remove(app.processName, app.uid);
10643 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010644 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010645 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10646 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010647 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010649 } else if (!app.removed) {
10650 // This app is persistent, so we need to keep its record around.
10651 // If it is not already on the pending app list, add it there
10652 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010653 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10654 mPersistentStartingProcesses.add(app);
10655 restart = true;
10656 }
10657 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010658 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10659 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010660 mProcessesOnHold.remove(app);
10661
The Android Open Source Project4df24232009-03-05 14:34:35 -080010662 if (app == mHomeProcess) {
10663 mHomeProcess = null;
10664 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010665 if (app == mPreviousProcess) {
10666 mPreviousProcess = null;
10667 }
10668
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010669 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010670 // We have components that still need to be running in the
10671 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010672 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010673 startProcessLocked(app, "restart", app.processName);
10674 } else if (app.pid > 0 && app.pid != MY_PID) {
10675 // Goodbye!
10676 synchronized (mPidsSelfLocked) {
10677 mPidsSelfLocked.remove(app.pid);
10678 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10679 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010680 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010681 }
10682 }
10683
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010684 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10685 // Look through the content providers we are waiting to have launched,
10686 // and if any run in this process then either schedule a restart of
10687 // the process or kill the client waiting for it if this process has
10688 // gone bad.
10689 int NL = mLaunchingProviders.size();
10690 boolean restart = false;
10691 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010692 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010693 if (cpr.launchingApp == app) {
10694 if (!alwaysBad && !app.bad) {
10695 restart = true;
10696 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010697 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010698 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010699 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010700 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010701 }
10702 }
10703 }
10704 return restart;
10705 }
10706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010707 // =========================================================
10708 // SERVICES
10709 // =========================================================
10710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010711 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10712 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010713 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010714 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010715 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010716 }
10717 }
10718
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010719 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010720 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010721 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010722 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010723 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010724 }
10725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010726 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010727 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010728 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010729 // Refuse possible leaked file descriptors
10730 if (service != null && service.hasFileDescriptors() == true) {
10731 throw new IllegalArgumentException("File descriptors passed in Intent");
10732 }
10733
Amith Yamasani742a6712011-05-04 14:49:28 -070010734 if (DEBUG_SERVICE)
10735 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010736 synchronized(this) {
10737 final int callingPid = Binder.getCallingPid();
10738 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010739 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010740 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010741 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010742 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010743 Binder.restoreCallingIdentity(origId);
10744 return res;
10745 }
10746 }
10747
10748 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010749 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010750 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010751 if (DEBUG_SERVICE)
10752 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010753 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010754 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010755 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010756 Binder.restoreCallingIdentity(origId);
10757 return res;
10758 }
10759 }
10760
10761 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010762 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010763 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010764 // Refuse possible leaked file descriptors
10765 if (service != null && service.hasFileDescriptors() == true) {
10766 throw new IllegalArgumentException("File descriptors passed in Intent");
10767 }
10768
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010769 checkValidCaller(Binder.getCallingUid(), userId);
10770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010771 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010772 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010774 }
10775
10776 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010777 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010778 // Refuse possible leaked file descriptors
10779 if (service != null && service.hasFileDescriptors() == true) {
10780 throw new IllegalArgumentException("File descriptors passed in Intent");
10781 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010782 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010783 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010785 }
10786
10787 public boolean stopServiceToken(ComponentName className, IBinder token,
10788 int startId) {
10789 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010790 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010792 }
10793
10794 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010795 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010796 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010797 mServices.setServiceForegroundLocked(className, token, id, notification,
10798 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010799 }
10800 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010801
Dianne Hackborn41203752012-08-31 14:05:51 -070010802 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10803 boolean requireFull, String name, String callerPackage) {
10804 synchronized(this) {
10805 return handleIncomingUserLocked(callingPid, callingUid, userId, allowAll,
10806 requireFull, name, callerPackage);
10807 }
10808 }
10809
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010810 int handleIncomingUserLocked(int callingPid, int callingUid, int userId, boolean allowAll,
10811 boolean requireFull, String name, String callerPackage) {
10812 final int callingUserId = UserHandle.getUserId(callingUid);
10813 if (callingUserId != userId) {
10814 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10815 if ((requireFull || checkComponentPermission(
10816 android.Manifest.permission.INTERACT_ACROSS_USERS,
10817 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10818 && checkComponentPermission(
10819 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10820 callingPid, callingUid, -1, true)
10821 != PackageManager.PERMISSION_GRANTED) {
10822 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10823 // In this case, they would like to just execute as their
10824 // owner user instead of failing.
10825 userId = callingUserId;
10826 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010827 StringBuilder builder = new StringBuilder(128);
10828 builder.append("Permission Denial: ");
10829 builder.append(name);
10830 if (callerPackage != null) {
10831 builder.append(" from ");
10832 builder.append(callerPackage);
10833 }
10834 builder.append(" asks to run as user ");
10835 builder.append(userId);
10836 builder.append(" but is calling from user ");
10837 builder.append(UserHandle.getUserId(callingUid));
10838 builder.append("; this requires ");
10839 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10840 if (!requireFull) {
10841 builder.append("or");
10842 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10843 }
10844 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010845 Slog.w(TAG, msg);
10846 throw new SecurityException(msg);
10847 }
10848 }
10849 }
10850 if (userId == UserHandle.USER_CURRENT
10851 || userId == UserHandle.USER_CURRENT_OR_SELF) {
10852 userId = mCurrentUserId;
10853 }
10854 if (!allowAll && userId < 0) {
10855 throw new IllegalArgumentException(
10856 "Call does not support special user #" + userId);
10857 }
10858 }
10859 return userId;
10860 }
10861
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010862 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10863 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010864 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010865 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010866 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10867 if (ActivityManager.checkUidPermission(
10868 android.Manifest.permission.INTERACT_ACROSS_USERS,
10869 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10870 ComponentName comp = new ComponentName(aInfo.packageName, className);
10871 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10872 + " requests FLAG_SINGLE_USER, but app does not hold "
10873 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10874 Slog.w(TAG, msg);
10875 throw new SecurityException(msg);
10876 }
10877 result = true;
10878 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010879 } else if (componentProcessName == aInfo.packageName) {
10880 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10881 } else if ("system".equals(componentProcessName)) {
10882 result = true;
10883 }
10884 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010885 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10886 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010887 }
10888 return result;
10889 }
10890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010891 public int bindService(IApplicationThread caller, IBinder token,
10892 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010893 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010894 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010895 // Refuse possible leaked file descriptors
10896 if (service != null && service.hasFileDescriptors() == true) {
10897 throw new IllegalArgumentException("File descriptors passed in Intent");
10898 }
10899
10900 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010901 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10902 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010903 }
10904 }
10905
10906 public boolean unbindService(IServiceConnection connection) {
10907 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010908 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010910 }
10911
10912 public void publishService(IBinder token, Intent intent, IBinder service) {
10913 // Refuse possible leaked file descriptors
10914 if (intent != null && intent.hasFileDescriptors() == true) {
10915 throw new IllegalArgumentException("File descriptors passed in Intent");
10916 }
10917
10918 synchronized(this) {
10919 if (!(token instanceof ServiceRecord)) {
10920 throw new IllegalArgumentException("Invalid service token");
10921 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010922 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010923 }
10924 }
10925
10926 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10927 // Refuse possible leaked file descriptors
10928 if (intent != null && intent.hasFileDescriptors() == true) {
10929 throw new IllegalArgumentException("File descriptors passed in Intent");
10930 }
10931
10932 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010933 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010934 }
10935 }
10936
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010937 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010938 synchronized(this) {
10939 if (!(token instanceof ServiceRecord)) {
10940 throw new IllegalArgumentException("Invalid service token");
10941 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010942 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010944 }
10945
10946 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010947 // BACKUP AND RESTORE
10948 // =========================================================
10949
10950 // Cause the target app to be launched if necessary and its backup agent
10951 // instantiated. The backup agent will invoke backupAgentCreated() on the
10952 // activity manager to announce its creation.
10953 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010954 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010955 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10956
10957 synchronized(this) {
10958 // !!! TODO: currently no check here that we're already bound
10959 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10960 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10961 synchronized (stats) {
10962 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10963 }
10964
Dianne Hackborne7f97212011-02-24 14:40:20 -080010965 // Backup agent is now in use, its package can't be stopped.
10966 try {
10967 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010968 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080010969 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010970 } catch (IllegalArgumentException e) {
10971 Slog.w(TAG, "Failed trying to unstop package "
10972 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010973 }
10974
Christopher Tate181fafa2009-05-14 11:12:14 -070010975 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070010976 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
10977 ? new ComponentName(app.packageName, app.backupAgentName)
10978 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070010979 // startProcessLocked() returns existing proc's record if it's already running
10980 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010981 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010982 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010983 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010984 return false;
10985 }
10986
10987 r.app = proc;
10988 mBackupTarget = r;
10989 mBackupAppName = app.packageName;
10990
Christopher Tate6fa95972009-06-05 18:43:55 -070010991 // Try not to kill the process during backup
10992 updateOomAdjLocked(proc);
10993
Christopher Tate181fafa2009-05-14 11:12:14 -070010994 // If the process is already attached, schedule the creation of the backup agent now.
10995 // If it is not yet live, this will be done when it attaches to the framework.
10996 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010997 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070010998 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010999 proc.thread.scheduleCreateBackupAgent(app,
11000 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011001 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011002 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011003 }
11004 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011005 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011006 }
11007 // Invariants: at this point, the target app process exists and the application
11008 // is either already running or in the process of coming up. mBackupTarget and
11009 // mBackupAppName describe the app, so that when it binds back to the AM we
11010 // know that it's scheduled for a backup-agent operation.
11011 }
11012
11013 return true;
11014 }
11015
11016 // A backup agent has just come up
11017 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011018 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011019 + " = " + agent);
11020
11021 synchronized(this) {
11022 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011023 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011024 return;
11025 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011026 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011027
Dianne Hackborn06740692010-09-22 22:46:21 -070011028 long oldIdent = Binder.clearCallingIdentity();
11029 try {
11030 IBackupManager bm = IBackupManager.Stub.asInterface(
11031 ServiceManager.getService(Context.BACKUP_SERVICE));
11032 bm.agentConnected(agentPackageName, agent);
11033 } catch (RemoteException e) {
11034 // can't happen; the backup manager service is local
11035 } catch (Exception e) {
11036 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11037 e.printStackTrace();
11038 } finally {
11039 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011040 }
11041 }
11042
11043 // done with this agent
11044 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011045 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011046 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011047 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011048 return;
11049 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011050
11051 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011052 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011053 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011054 return;
11055 }
11056
Christopher Tate181fafa2009-05-14 11:12:14 -070011057 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011058 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011059 return;
11060 }
11061
Christopher Tate6fa95972009-06-05 18:43:55 -070011062 ProcessRecord proc = mBackupTarget.app;
11063 mBackupTarget = null;
11064 mBackupAppName = null;
11065
11066 // Not backing this app up any more; reset its OOM adjustment
11067 updateOomAdjLocked(proc);
11068
Christopher Tatec7b31e32009-06-10 15:49:30 -070011069 // If the app crashed during backup, 'thread' will be null here
11070 if (proc.thread != null) {
11071 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011072 proc.thread.scheduleDestroyBackupAgent(appInfo,
11073 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070011074 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011075 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070011076 e.printStackTrace();
11077 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011078 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011079 }
11080 }
11081 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011082 // BROADCASTS
11083 // =========================================================
11084
Josh Bartel7f208742010-02-25 11:01:44 -060011085 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011086 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011087 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011088 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11089 if (stickies == null) {
11090 return cur;
11091 }
11092 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011093 if (list == null) {
11094 return cur;
11095 }
11096 int N = list.size();
11097 for (int i=0; i<N; i++) {
11098 Intent intent = list.get(i);
11099 if (filter.match(resolver, intent, true, TAG) >= 0) {
11100 if (cur == null) {
11101 cur = new ArrayList<Intent>();
11102 }
11103 cur.add(intent);
11104 }
11105 }
11106 return cur;
11107 }
11108
Christopher Tatef46723b2012-01-26 14:19:24 -080011109 boolean isPendingBroadcastProcessLocked(int pid) {
11110 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11111 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011113
Christopher Tatef46723b2012-01-26 14:19:24 -080011114 void skipPendingBroadcastLocked(int pid) {
11115 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11116 for (BroadcastQueue queue : mBroadcastQueues) {
11117 queue.skipPendingBroadcastLocked(pid);
11118 }
11119 }
11120
11121 // The app just attached; send any pending broadcasts that it should receive
11122 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11123 boolean didSomething = false;
11124 for (BroadcastQueue queue : mBroadcastQueues) {
11125 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011126 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011127 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011128 }
11129
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011130 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011131 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011132 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011133 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011134 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011135 synchronized(this) {
11136 ProcessRecord callerApp = null;
11137 if (caller != null) {
11138 callerApp = getRecordForAppLocked(caller);
11139 if (callerApp == null) {
11140 throw new SecurityException(
11141 "Unable to find app for caller " + caller
11142 + " (pid=" + Binder.getCallingPid()
11143 + ") when registering receiver " + receiver);
11144 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011145 if (callerApp.info.uid != Process.SYSTEM_UID &&
11146 !callerApp.pkgList.contains(callerPackage)) {
11147 throw new SecurityException("Given caller package " + callerPackage
11148 + " is not running in process " + callerApp);
11149 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011150 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011151 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011152 } else {
11153 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011154 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011155 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011156 }
11157
Dianne Hackborn20e80982012-08-31 19:00:44 -070011158 userId = this.handleIncomingUserLocked(callingPid, callingUid, userId,
11159 true, true, "registerReceiver", callerPackage);
11160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011161 List allSticky = null;
11162
11163 // Look for any matching sticky broadcasts...
11164 Iterator actions = filter.actionsIterator();
11165 if (actions != null) {
11166 while (actions.hasNext()) {
11167 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011168 allSticky = getStickiesLocked(action, filter, allSticky,
11169 UserHandle.USER_ALL);
11170 allSticky = getStickiesLocked(action, filter, allSticky,
11171 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011172 }
11173 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011174 allSticky = getStickiesLocked(null, filter, allSticky,
11175 UserHandle.USER_ALL);
11176 allSticky = getStickiesLocked(null, filter, allSticky,
11177 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011178 }
11179
11180 // The first sticky in the list is returned directly back to
11181 // the client.
11182 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11183
Joe Onorato8a9b2202010-02-26 18:56:32 -080011184 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011185 + ": " + sticky);
11186
11187 if (receiver == null) {
11188 return sticky;
11189 }
11190
11191 ReceiverList rl
11192 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11193 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011194 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11195 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011196 if (rl.app != null) {
11197 rl.app.receivers.add(rl);
11198 } else {
11199 try {
11200 receiver.asBinder().linkToDeath(rl, 0);
11201 } catch (RemoteException e) {
11202 return sticky;
11203 }
11204 rl.linkedToDeath = true;
11205 }
11206 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011207 } else if (rl.uid != callingUid) {
11208 throw new IllegalArgumentException(
11209 "Receiver requested to register for uid " + callingUid
11210 + " was previously registered for uid " + rl.uid);
11211 } else if (rl.pid != callingPid) {
11212 throw new IllegalArgumentException(
11213 "Receiver requested to register for pid " + callingPid
11214 + " was previously registered for pid " + rl.pid);
11215 } else if (rl.userId != userId) {
11216 throw new IllegalArgumentException(
11217 "Receiver requested to register for user " + userId
11218 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011219 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011220 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011221 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011222 rl.add(bf);
11223 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011224 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011225 }
11226 mReceiverResolver.addFilter(bf);
11227
11228 // Enqueue broadcasts for all existing stickies that match
11229 // this filter.
11230 if (allSticky != null) {
11231 ArrayList receivers = new ArrayList();
11232 receivers.add(bf);
11233
11234 int N = allSticky.size();
11235 for (int i=0; i<N; i++) {
11236 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011237 BroadcastQueue queue = broadcastQueueForIntent(intent);
11238 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011239 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011240 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011241 queue.enqueueParallelBroadcastLocked(r);
11242 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011243 }
11244 }
11245
11246 return sticky;
11247 }
11248 }
11249
11250 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011251 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011252
Christopher Tatef46723b2012-01-26 14:19:24 -080011253 final long origId = Binder.clearCallingIdentity();
11254 try {
11255 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256
Christopher Tatef46723b2012-01-26 14:19:24 -080011257 synchronized(this) {
11258 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011259 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011260 if (rl != null) {
11261 if (rl.curBroadcast != null) {
11262 BroadcastRecord r = rl.curBroadcast;
11263 final boolean doNext = finishReceiverLocked(
11264 receiver.asBinder(), r.resultCode, r.resultData,
11265 r.resultExtras, r.resultAbort, true);
11266 if (doNext) {
11267 doTrim = true;
11268 r.queue.processNextBroadcast(false);
11269 }
11270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011271
Christopher Tatef46723b2012-01-26 14:19:24 -080011272 if (rl.app != null) {
11273 rl.app.receivers.remove(rl);
11274 }
11275 removeReceiverLocked(rl);
11276 if (rl.linkedToDeath) {
11277 rl.linkedToDeath = false;
11278 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011280 }
11281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282
Christopher Tatef46723b2012-01-26 14:19:24 -080011283 // If we actually concluded any broadcasts, we might now be able
11284 // to trim the recipients' apps from our working set
11285 if (doTrim) {
11286 trimApplications();
11287 return;
11288 }
11289
11290 } finally {
11291 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011293 }
11294
11295 void removeReceiverLocked(ReceiverList rl) {
11296 mRegisteredReceivers.remove(rl.receiver.asBinder());
11297 int N = rl.size();
11298 for (int i=0; i<N; i++) {
11299 mReceiverResolver.removeFilter(rl.get(i));
11300 }
11301 }
11302
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011303 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011304 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11305 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011306 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011307 try {
11308 r.thread.dispatchPackageBroadcast(cmd, packages);
11309 } catch (RemoteException ex) {
11310 }
11311 }
11312 }
11313 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011314
11315 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11316 int[] users) {
11317 List<ResolveInfo> receivers = null;
11318 try {
11319 HashSet<ComponentName> singleUserReceivers = null;
11320 boolean scannedFirstReceivers = false;
11321 for (int user : users) {
11322 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11323 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
11324 if (newReceivers != null && newReceivers.size() == 0) {
11325 newReceivers = null;
11326 }
11327 if (receivers == null) {
11328 receivers = newReceivers;
11329 } else if (newReceivers != null) {
11330 // We need to concatenate the additional receivers
11331 // found with what we have do far. This would be easy,
11332 // but we also need to de-dup any receivers that are
11333 // singleUser.
11334 if (!scannedFirstReceivers) {
11335 // Collect any single user receivers we had already retrieved.
11336 scannedFirstReceivers = true;
11337 for (int i=0; i<receivers.size(); i++) {
11338 ResolveInfo ri = receivers.get(i);
11339 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11340 ComponentName cn = new ComponentName(
11341 ri.activityInfo.packageName, ri.activityInfo.name);
11342 if (singleUserReceivers == null) {
11343 singleUserReceivers = new HashSet<ComponentName>();
11344 }
11345 singleUserReceivers.add(cn);
11346 }
11347 }
11348 }
11349 // Add the new results to the existing results, tracking
11350 // and de-dupping single user receivers.
11351 for (int i=0; i<newReceivers.size(); i++) {
11352 ResolveInfo ri = receivers.get(i);
11353 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11354 ComponentName cn = new ComponentName(
11355 ri.activityInfo.packageName, ri.activityInfo.name);
11356 if (singleUserReceivers == null) {
11357 singleUserReceivers = new HashSet<ComponentName>();
11358 }
11359 if (!singleUserReceivers.contains(cn)) {
11360 singleUserReceivers.add(cn);
11361 receivers.add(ri);
11362 }
11363 } else {
11364 receivers.add(ri);
11365 }
11366 }
11367 }
11368 }
11369 } catch (RemoteException ex) {
11370 // pm is in same process, this will never happen.
11371 }
11372 return receivers;
11373 }
11374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011375 private final int broadcastIntentLocked(ProcessRecord callerApp,
11376 String callerPackage, Intent intent, String resolvedType,
11377 IIntentReceiver resultTo, int resultCode, String resultData,
11378 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011379 boolean ordered, boolean sticky, int callingPid, int callingUid,
11380 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011381 intent = new Intent(intent);
11382
Dianne Hackborne7f97212011-02-24 14:40:20 -080011383 // By default broadcasts do not go to stopped apps.
11384 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11385
Joe Onorato8a9b2202010-02-26 18:56:32 -080011386 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011387 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011388 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011389 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011390 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011391 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011392
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011393 userId = handleIncomingUserLocked(callingPid, callingUid, userId,
11394 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011395
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011396 // Make sure that the user who is receiving this broadcast is started
11397 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011398 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011399 Slog.w(TAG, "Skipping broadcast of " + intent
11400 + ": user " + userId + " is stopped");
11401 return ActivityManager.BROADCAST_SUCCESS;
11402 }
11403
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011404 /*
11405 * Prevent non-system code (defined here to be non-persistent
11406 * processes) from sending protected broadcasts.
11407 */
11408 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11409 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11410 callingUid == 0) {
11411 // Always okay.
11412 } else if (callerApp == null || !callerApp.persistent) {
11413 try {
11414 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11415 intent.getAction())) {
11416 String msg = "Permission Denial: not allowed to send broadcast "
11417 + intent.getAction() + " from pid="
11418 + callingPid + ", uid=" + callingUid;
11419 Slog.w(TAG, msg);
11420 throw new SecurityException(msg);
11421 }
11422 } catch (RemoteException e) {
11423 Slog.w(TAG, "Remote exception", e);
11424 return ActivityManager.BROADCAST_SUCCESS;
11425 }
11426 }
11427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011428 // Handle special intents: if this broadcast is from the package
11429 // manager about a package being removed, we need to remove all of
11430 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011431 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011432 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011433 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11434 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011435 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011436 || uidRemoved) {
11437 if (checkComponentPermission(
11438 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011439 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011440 == PackageManager.PERMISSION_GRANTED) {
11441 if (uidRemoved) {
11442 final Bundle intentExtras = intent.getExtras();
11443 final int uid = intentExtras != null
11444 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11445 if (uid >= 0) {
11446 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11447 synchronized (bs) {
11448 bs.removeUidStatsLocked(uid);
11449 }
11450 }
11451 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011452 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011453 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011454 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011455 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11456 if (list != null && (list.length > 0)) {
11457 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011458 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011459 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011460 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011461 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011462 }
11463 } else {
11464 Uri data = intent.getData();
11465 String ssp;
11466 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11467 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11468 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011469 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11470 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011471 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011472 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011473 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011474 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011476 }
11477 }
11478 }
11479 } else {
11480 String msg = "Permission Denial: " + intent.getAction()
11481 + " broadcast from " + callerPackage + " (pid=" + callingPid
11482 + ", uid=" + callingUid + ")"
11483 + " requires "
11484 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011485 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011486 throw new SecurityException(msg);
11487 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011488
11489 // Special case for adding a package: by default turn on compatibility
11490 // mode.
11491 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011492 Uri data = intent.getData();
11493 String ssp;
11494 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11495 mCompatModePackages.handlePackageAddedLocked(ssp,
11496 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011498 }
11499
11500 /*
11501 * If this is the time zone changed action, queue up a message that will reset the timezone
11502 * of all currently running processes. This message will get queued up before the broadcast
11503 * happens.
11504 */
11505 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11506 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11507 }
11508
Robert Greenwalt03595d02010-11-02 14:08:23 -070011509 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11510 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11511 }
11512
Robert Greenwalt434203a2010-10-11 16:00:27 -070011513 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11514 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11515 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11516 }
11517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011518 // Add to the sticky list if requested.
11519 if (sticky) {
11520 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11521 callingPid, callingUid)
11522 != PackageManager.PERMISSION_GRANTED) {
11523 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11524 + callingPid + ", uid=" + callingUid
11525 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011526 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011527 throw new SecurityException(msg);
11528 }
11529 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011530 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011531 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011532 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011533 }
11534 if (intent.getComponent() != null) {
11535 throw new SecurityException(
11536 "Sticky broadcasts can't target a specific component");
11537 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011538 // We use userId directly here, since the "all" target is maintained
11539 // as a separate set of sticky broadcasts.
11540 if (userId != UserHandle.USER_ALL) {
11541 // But first, if this is not a broadcast to all users, then
11542 // make sure it doesn't conflict with an existing broadcast to
11543 // all users.
11544 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11545 UserHandle.USER_ALL);
11546 if (stickies != null) {
11547 ArrayList<Intent> list = stickies.get(intent.getAction());
11548 if (list != null) {
11549 int N = list.size();
11550 int i;
11551 for (i=0; i<N; i++) {
11552 if (intent.filterEquals(list.get(i))) {
11553 throw new IllegalArgumentException(
11554 "Sticky broadcast " + intent + " for user "
11555 + userId + " conflicts with existing global broadcast");
11556 }
11557 }
11558 }
11559 }
11560 }
11561 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11562 if (stickies == null) {
11563 stickies = new HashMap<String, ArrayList<Intent>>();
11564 mStickyBroadcasts.put(userId, stickies);
11565 }
11566 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011567 if (list == null) {
11568 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011569 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011570 }
11571 int N = list.size();
11572 int i;
11573 for (i=0; i<N; i++) {
11574 if (intent.filterEquals(list.get(i))) {
11575 // This sticky already exists, replace it.
11576 list.set(i, new Intent(intent));
11577 break;
11578 }
11579 }
11580 if (i >= N) {
11581 list.add(new Intent(intent));
11582 }
11583 }
11584
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011585 int[] users;
11586 if (userId == UserHandle.USER_ALL) {
11587 // Caller wants broadcast to go to all started users.
11588 users = new int[mStartedUsers.size()];
11589 for (int i=0; i<mStartedUsers.size(); i++) {
11590 users[i] = mStartedUsers.keyAt(i);
11591 }
11592 } else {
11593 // Caller wants broadcast to go to one specific user.
11594 users = new int[] {userId};
11595 }
11596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011597 // Figure out who all will receive this broadcast.
11598 List receivers = null;
11599 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011600 // Need to resolve the intent to interested receivers...
11601 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11602 == 0) {
11603 receivers = collectReceiverComponents(intent, resolvedType, users);
11604 }
11605 if (intent.getComponent() == null) {
11606 registeredReceivers = mReceiverResolver.queryIntent(intent,
11607 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011608 }
11609
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011610 final boolean replacePending =
11611 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11612
Joe Onorato8a9b2202010-02-26 18:56:32 -080011613 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011614 + " replacePending=" + replacePending);
11615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011616 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11617 if (!ordered && NR > 0) {
11618 // If we are not serializing this broadcast, then send the
11619 // registered receivers separately so they don't wait for the
11620 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011621 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11622 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011623 callerPackage, callingPid, callingUid, requiredPermission,
11624 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011625 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011626 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011627 TAG, "Enqueueing parallel broadcast " + r);
11628 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011629 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011630 queue.enqueueParallelBroadcastLocked(r);
11631 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011633 registeredReceivers = null;
11634 NR = 0;
11635 }
11636
11637 // Merge into one list.
11638 int ir = 0;
11639 if (receivers != null) {
11640 // A special case for PACKAGE_ADDED: do not allow the package
11641 // being added to see this broadcast. This prevents them from
11642 // using this as a back door to get run as soon as they are
11643 // installed. Maybe in the future we want to have a special install
11644 // broadcast or such for apps, but we'd like to deliberately make
11645 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011646 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011647 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11648 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11649 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011650 Uri data = intent.getData();
11651 if (data != null) {
11652 String pkgName = data.getSchemeSpecificPart();
11653 if (pkgName != null) {
11654 skipPackages = new String[] { pkgName };
11655 }
11656 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011657 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011658 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011659 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011660 if (skipPackages != null && (skipPackages.length > 0)) {
11661 for (String skipPackage : skipPackages) {
11662 if (skipPackage != null) {
11663 int NT = receivers.size();
11664 for (int it=0; it<NT; it++) {
11665 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11666 if (curt.activityInfo.packageName.equals(skipPackage)) {
11667 receivers.remove(it);
11668 it--;
11669 NT--;
11670 }
11671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011672 }
11673 }
11674 }
11675
11676 int NT = receivers != null ? receivers.size() : 0;
11677 int it = 0;
11678 ResolveInfo curt = null;
11679 BroadcastFilter curr = null;
11680 while (it < NT && ir < NR) {
11681 if (curt == null) {
11682 curt = (ResolveInfo)receivers.get(it);
11683 }
11684 if (curr == null) {
11685 curr = registeredReceivers.get(ir);
11686 }
11687 if (curr.getPriority() >= curt.priority) {
11688 // Insert this broadcast record into the final list.
11689 receivers.add(it, curr);
11690 ir++;
11691 curr = null;
11692 it++;
11693 NT++;
11694 } else {
11695 // Skip to the next ResolveInfo in the final list.
11696 it++;
11697 curt = null;
11698 }
11699 }
11700 }
11701 while (ir < NR) {
11702 if (receivers == null) {
11703 receivers = new ArrayList();
11704 }
11705 receivers.add(registeredReceivers.get(ir));
11706 ir++;
11707 }
11708
11709 if ((receivers != null && receivers.size() > 0)
11710 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011711 BroadcastQueue queue = broadcastQueueForIntent(intent);
11712 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011713 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011714 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011715 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011716 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011717 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011718 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011719 if (DEBUG_BROADCAST) {
11720 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011721 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011722 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011723 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011724 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011725 queue.enqueueOrderedBroadcastLocked(r);
11726 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011728 }
11729
Dianne Hackborna4972e92012-03-14 10:38:05 -070011730 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011731 }
11732
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011733 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011734 // Refuse possible leaked file descriptors
11735 if (intent != null && intent.hasFileDescriptors() == true) {
11736 throw new IllegalArgumentException("File descriptors passed in Intent");
11737 }
11738
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011739 int flags = intent.getFlags();
11740
11741 if (!mProcessesReady) {
11742 // if the caller really truly claims to know what they're doing, go
11743 // ahead and allow the broadcast without launching any receivers
11744 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11745 intent = new Intent(intent);
11746 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11747 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11748 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11749 + " before boot completion");
11750 throw new IllegalStateException("Cannot broadcast before boot completed");
11751 }
11752 }
11753
11754 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11755 throw new IllegalArgumentException(
11756 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11757 }
11758
11759 return intent;
11760 }
11761
11762 public final int broadcastIntent(IApplicationThread caller,
11763 Intent intent, String resolvedType, IIntentReceiver resultTo,
11764 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011765 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011766 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011767 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011768 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011770 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11771 final int callingPid = Binder.getCallingPid();
11772 final int callingUid = Binder.getCallingUid();
11773 final long origId = Binder.clearCallingIdentity();
11774 int res = broadcastIntentLocked(callerApp,
11775 callerApp != null ? callerApp.info.packageName : null,
11776 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011777 resultCode, resultData, map, requiredPermission, serialized, sticky,
11778 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011779 Binder.restoreCallingIdentity(origId);
11780 return res;
11781 }
11782 }
11783
11784 int broadcastIntentInPackage(String packageName, int uid,
11785 Intent intent, String resolvedType, IIntentReceiver resultTo,
11786 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011787 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011788 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011789 intent = verifyBroadcastLocked(intent);
11790
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011791 final long origId = Binder.clearCallingIdentity();
11792 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11793 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011794 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011795 Binder.restoreCallingIdentity(origId);
11796 return res;
11797 }
11798 }
11799
Amith Yamasani742a6712011-05-04 14:49:28 -070011800 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011801 // Refuse possible leaked file descriptors
11802 if (intent != null && intent.hasFileDescriptors() == true) {
11803 throw new IllegalArgumentException("File descriptors passed in Intent");
11804 }
11805
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011806 userId = handleIncomingUserLocked(Binder.getCallingPid(),
11807 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011809 synchronized(this) {
11810 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11811 != PackageManager.PERMISSION_GRANTED) {
11812 String msg = "Permission Denial: unbroadcastIntent() from pid="
11813 + Binder.getCallingPid()
11814 + ", uid=" + Binder.getCallingUid()
11815 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011816 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011817 throw new SecurityException(msg);
11818 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011819 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11820 if (stickies != null) {
11821 ArrayList<Intent> list = stickies.get(intent.getAction());
11822 if (list != null) {
11823 int N = list.size();
11824 int i;
11825 for (i=0; i<N; i++) {
11826 if (intent.filterEquals(list.get(i))) {
11827 list.remove(i);
11828 break;
11829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011830 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011831 if (list.size() <= 0) {
11832 stickies.remove(intent.getAction());
11833 }
11834 }
11835 if (stickies.size() <= 0) {
11836 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011837 }
11838 }
11839 }
11840 }
11841
11842 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11843 String resultData, Bundle resultExtras, boolean resultAbort,
11844 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011845 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11846 if (r == null) {
11847 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011848 return false;
11849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011850
Christopher Tatef46723b2012-01-26 14:19:24 -080011851 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11852 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011853 }
11854
11855 public void finishReceiver(IBinder who, int resultCode, String resultData,
11856 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011857 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011858
11859 // Refuse possible leaked file descriptors
11860 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11861 throw new IllegalArgumentException("File descriptors passed in Bundle");
11862 }
11863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011864 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011865 try {
11866 boolean doNext = false;
11867 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011868
Christopher Tatef46723b2012-01-26 14:19:24 -080011869 synchronized(this) {
11870 r = broadcastRecordForReceiverLocked(who);
11871 if (r != null) {
11872 doNext = r.queue.finishReceiverLocked(r, resultCode,
11873 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011875 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011876
Christopher Tatef46723b2012-01-26 14:19:24 -080011877 if (doNext) {
11878 r.queue.processNextBroadcast(false);
11879 }
11880 trimApplications();
11881 } finally {
11882 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011883 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011886 // =========================================================
11887 // INSTRUMENTATION
11888 // =========================================================
11889
11890 public boolean startInstrumentation(ComponentName className,
11891 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011892 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011893 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011894 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
11895 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011896 // Refuse possible leaked file descriptors
11897 if (arguments != null && arguments.hasFileDescriptors()) {
11898 throw new IllegalArgumentException("File descriptors passed in Bundle");
11899 }
11900
11901 synchronized(this) {
11902 InstrumentationInfo ii = null;
11903 ApplicationInfo ai = null;
11904 try {
11905 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011906 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011907 ai = AppGlobals.getPackageManager().getApplicationInfo(
11908 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011909 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011910 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011911 }
11912 if (ii == null) {
11913 reportStartInstrumentationFailure(watcher, className,
11914 "Unable to find instrumentation info for: " + className);
11915 return false;
11916 }
11917 if (ai == null) {
11918 reportStartInstrumentationFailure(watcher, className,
11919 "Unable to find instrumentation target package: " + ii.targetPackage);
11920 return false;
11921 }
11922
11923 int match = mContext.getPackageManager().checkSignatures(
11924 ii.targetPackage, ii.packageName);
11925 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11926 String msg = "Permission Denial: starting instrumentation "
11927 + className + " from pid="
11928 + Binder.getCallingPid()
11929 + ", uid=" + Binder.getCallingPid()
11930 + " not allowed because package " + ii.packageName
11931 + " does not have a signature matching the target "
11932 + ii.targetPackage;
11933 reportStartInstrumentationFailure(watcher, className, msg);
11934 throw new SecurityException(msg);
11935 }
11936
11937 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070011938 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070011939 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011940 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011941 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011942 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011943 app.instrumentationProfileFile = profileFile;
11944 app.instrumentationArguments = arguments;
11945 app.instrumentationWatcher = watcher;
11946 app.instrumentationResultClass = className;
11947 Binder.restoreCallingIdentity(origId);
11948 }
11949
11950 return true;
11951 }
11952
11953 /**
11954 * Report errors that occur while attempting to start Instrumentation. Always writes the
11955 * error to the logs, but if somebody is watching, send the report there too. This enables
11956 * the "am" command to report errors with more information.
11957 *
11958 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11959 * @param cn The component name of the instrumentation.
11960 * @param report The error report.
11961 */
11962 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11963 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011964 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011965 try {
11966 if (watcher != null) {
11967 Bundle results = new Bundle();
11968 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11969 results.putString("Error", report);
11970 watcher.instrumentationStatus(cn, -1, results);
11971 }
11972 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011973 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011974 }
11975 }
11976
11977 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
11978 if (app.instrumentationWatcher != null) {
11979 try {
11980 // NOTE: IInstrumentationWatcher *must* be oneway here
11981 app.instrumentationWatcher.instrumentationFinished(
11982 app.instrumentationClass,
11983 resultCode,
11984 results);
11985 } catch (RemoteException e) {
11986 }
11987 }
11988 app.instrumentationWatcher = null;
11989 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011990 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011991 app.instrumentationProfileFile = null;
11992 app.instrumentationArguments = null;
11993
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011994 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011995 }
11996
11997 public void finishInstrumentation(IApplicationThread target,
11998 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011999 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012000 // Refuse possible leaked file descriptors
12001 if (results != null && results.hasFileDescriptors()) {
12002 throw new IllegalArgumentException("File descriptors passed in Intent");
12003 }
12004
12005 synchronized(this) {
12006 ProcessRecord app = getRecordForAppLocked(target);
12007 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012008 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012009 return;
12010 }
12011 final long origId = Binder.clearCallingIdentity();
12012 finishInstrumentationLocked(app, resultCode, results);
12013 Binder.restoreCallingIdentity(origId);
12014 }
12015 }
12016
12017 // =========================================================
12018 // CONFIGURATION
12019 // =========================================================
12020
12021 public ConfigurationInfo getDeviceConfigurationInfo() {
12022 ConfigurationInfo config = new ConfigurationInfo();
12023 synchronized (this) {
12024 config.reqTouchScreen = mConfiguration.touchscreen;
12025 config.reqKeyboardType = mConfiguration.keyboard;
12026 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012027 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12028 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012029 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12030 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012031 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12032 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012033 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12034 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012035 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012036 }
12037 return config;
12038 }
12039
12040 public Configuration getConfiguration() {
12041 Configuration ci;
12042 synchronized(this) {
12043 ci = new Configuration(mConfiguration);
12044 }
12045 return ci;
12046 }
12047
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012048 public void updatePersistentConfiguration(Configuration values) {
12049 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12050 "updateConfiguration()");
12051 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12052 "updateConfiguration()");
12053 if (values == null) {
12054 throw new NullPointerException("Configuration must not be null");
12055 }
12056
12057 synchronized(this) {
12058 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012059 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012060 Binder.restoreCallingIdentity(origId);
12061 }
12062 }
12063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012064 public void updateConfiguration(Configuration values) {
12065 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12066 "updateConfiguration()");
12067
12068 synchronized(this) {
12069 if (values == null && mWindowManager != null) {
12070 // sentinel: fetch the current configuration from the window manager
12071 values = mWindowManager.computeNewConfiguration();
12072 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012073
12074 if (mWindowManager != null) {
12075 mProcessList.applyDisplaySize(mWindowManager);
12076 }
12077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012078 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012079 if (values != null) {
12080 Settings.System.clearConfiguration(values);
12081 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012082 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012083 Binder.restoreCallingIdentity(origId);
12084 }
12085 }
12086
12087 /**
12088 * Do either or both things: (1) change the current configuration, and (2)
12089 * make sure the given activity is running with the (now) current
12090 * configuration. Returns true if the activity has been left running, or
12091 * false if <var>starting</var> is being destroyed to match the new
12092 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012093 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012094 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012095 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012096 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012097 // do nothing if we are headless
12098 if (mHeadless) return true;
12099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012100 int changes = 0;
12101
12102 boolean kept = true;
12103
12104 if (values != null) {
12105 Configuration newConfig = new Configuration(mConfiguration);
12106 changes = newConfig.updateFrom(values);
12107 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012108 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012109 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012110 }
12111
Doug Zongker2bec3d42009-12-04 12:52:44 -080012112 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012113
Dianne Hackborn813075a62011-11-14 17:45:19 -080012114 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012115 saveLocaleLocked(values.locale,
12116 !values.locale.equals(mConfiguration.locale),
12117 values.userSetLocale);
12118 }
12119
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012120 mConfigurationSeq++;
12121 if (mConfigurationSeq <= 0) {
12122 mConfigurationSeq = 1;
12123 }
12124 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012125 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012126 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012127
12128 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012129
12130 // TODO: If our config changes, should we auto dismiss any currently
12131 // showing dialogs?
12132 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012133
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012134 AttributeCache ac = AttributeCache.instance();
12135 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012136 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012137 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012138
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012139 // Make sure all resources in our process are updated
12140 // right now, so that anyone who is going to retrieve
12141 // resource values after we return will be sure to get
12142 // the new ones. This is especially important during
12143 // boot, where the first config change needs to guarantee
12144 // all resources have that config before following boot
12145 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012146 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012147
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012148 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012149 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012150 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012151 mHandler.sendMessage(msg);
12152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012153
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012154 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12155 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012156 try {
12157 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012158 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012159 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012160 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012161 }
12162 } catch (Exception e) {
12163 }
12164 }
12165 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012166 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12167 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012168 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012169 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012170 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12171 broadcastIntentLocked(null, null,
12172 new Intent(Intent.ACTION_LOCALE_CHANGED),
12173 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012174 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012176 }
12177 }
12178
12179 if (changes != 0 && starting == null) {
12180 // If the configuration changed, and the caller is not already
12181 // in the process of starting an activity, then find the top
12182 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012183 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012184 }
12185
12186 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012187 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012188 // And we need to make sure at this point that all other activities
12189 // are made visible with the correct configuration.
12190 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012191 }
12192
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012193 if (values != null && mWindowManager != null) {
12194 mWindowManager.setNewConfiguration(mConfiguration);
12195 }
12196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012197 return kept;
12198 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012199
12200 /**
12201 * Decide based on the configuration whether we should shouw the ANR,
12202 * crash, etc dialogs. The idea is that if there is no affordnace to
12203 * press the on-screen buttons, we shouldn't show the dialog.
12204 *
12205 * A thought: SystemUI might also want to get told about this, the Power
12206 * dialog / global actions also might want different behaviors.
12207 */
12208 private static final boolean shouldShowDialogs(Configuration config) {
12209 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12210 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012212
12213 /**
12214 * Save the locale. You must be inside a synchronized (this) block.
12215 */
12216 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12217 if(isDiff) {
12218 SystemProperties.set("user.language", l.getLanguage());
12219 SystemProperties.set("user.region", l.getCountry());
12220 }
12221
12222 if(isPersist) {
12223 SystemProperties.set("persist.sys.language", l.getLanguage());
12224 SystemProperties.set("persist.sys.country", l.getCountry());
12225 SystemProperties.set("persist.sys.localevar", l.getVariant());
12226 }
12227 }
12228
Adam Powelldd8fab22012-03-22 17:47:27 -070012229 @Override
12230 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12231 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012232 return srec != null && srec.task.affinity != null &&
12233 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012234 }
12235
12236 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12237 Intent resultData) {
12238 ComponentName dest = destIntent.getComponent();
12239
12240 synchronized (this) {
12241 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012242 if (srec == null) {
12243 return false;
12244 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012245 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12246 final int start = history.indexOf(srec);
12247 if (start < 0) {
12248 // Current activity is not in history stack; do nothing.
12249 return false;
12250 }
12251 int finishTo = start - 1;
12252 ActivityRecord parent = null;
12253 boolean foundParentInTask = false;
12254 if (dest != null) {
12255 TaskRecord tr = srec.task;
12256 for (int i = start - 1; i >= 0; i--) {
12257 ActivityRecord r = history.get(i);
12258 if (tr != r.task) {
12259 // Couldn't find parent in the same task; stop at the one above this.
12260 // (Root of current task; in-app "home" behavior)
12261 // Always at least finish the current activity.
12262 finishTo = Math.min(start - 1, i + 1);
12263 parent = history.get(finishTo);
12264 break;
12265 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12266 r.info.name.equals(dest.getClassName())) {
12267 finishTo = i;
12268 parent = r;
12269 foundParentInTask = true;
12270 break;
12271 }
12272 }
12273 }
12274
12275 if (mController != null) {
12276 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12277 if (next != null) {
12278 // ask watcher if this is allowed
12279 boolean resumeOK = true;
12280 try {
12281 resumeOK = mController.activityResuming(next.packageName);
12282 } catch (RemoteException e) {
12283 mController = null;
12284 }
12285
12286 if (!resumeOK) {
12287 return false;
12288 }
12289 }
12290 }
12291 final long origId = Binder.clearCallingIdentity();
12292 for (int i = start; i > finishTo; i--) {
12293 ActivityRecord r = history.get(i);
12294 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
12295 "navigate-up");
12296 // Only return the supplied result for the first activity finished
12297 resultCode = Activity.RESULT_CANCELED;
12298 resultData = null;
12299 }
12300
12301 if (parent != null && foundParentInTask) {
12302 final int parentLaunchMode = parent.info.launchMode;
12303 final int destIntentFlags = destIntent.getFlags();
12304 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12305 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12306 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12307 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012308 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012309 } else {
12310 try {
12311 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012312 destIntent.getComponent(), 0, UserHandle.getCallingUserId());
Adam Powelldd8fab22012-03-22 17:47:27 -070012313 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12314 null, aInfo, parent.appToken, null,
12315 0, -1, parent.launchedFromUid, 0, null, true, null);
12316 foundParentInTask = res == ActivityManager.START_SUCCESS;
12317 } catch (RemoteException e) {
12318 foundParentInTask = false;
12319 }
12320 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
12321 resultData, "navigate-up");
12322 }
12323 }
12324 Binder.restoreCallingIdentity(origId);
12325 return foundParentInTask;
12326 }
12327 }
12328
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012329 public int getLaunchedFromUid(IBinder activityToken) {
12330 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12331 if (srec == null) {
12332 return -1;
12333 }
12334 return srec.launchedFromUid;
12335 }
12336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012337 // =========================================================
12338 // LIFETIME MANAGEMENT
12339 // =========================================================
12340
Christopher Tatef46723b2012-01-26 14:19:24 -080012341 // Returns which broadcast queue the app is the current [or imminent] receiver
12342 // on, or 'null' if the app is not an active broadcast recipient.
12343 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12344 BroadcastRecord r = app.curReceiver;
12345 if (r != null) {
12346 return r.queue;
12347 }
12348
12349 // It's not the current receiver, but it might be starting up to become one
12350 synchronized (this) {
12351 for (BroadcastQueue queue : mBroadcastQueues) {
12352 r = queue.mPendingBroadcast;
12353 if (r != null && r.curApp == app) {
12354 // found it; report which queue it's in
12355 return queue;
12356 }
12357 }
12358 }
12359
12360 return null;
12361 }
12362
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012363 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012364 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012365 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012366 // This adjustment has already been computed. If we are calling
12367 // from the top, we may have already computed our adjustment with
12368 // an earlier hidden adjustment that isn't really for us... if
12369 // so, use the new hidden adjustment.
12370 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012371 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
12372 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012373 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012374 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012375 }
12376
12377 if (app.thread == null) {
12378 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012379 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012380 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012381 }
12382
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012383 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12384 app.adjSource = null;
12385 app.adjTarget = null;
12386 app.empty = false;
12387 app.hidden = false;
12388
12389 final int activitiesSize = app.activities.size();
12390
Dianne Hackborn7d608422011-08-07 16:24:18 -070012391 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012392 // The max adjustment doesn't allow this app to be anything
12393 // below foreground, so it is not worth doing work for it.
12394 app.adjType = "fixed";
12395 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012396 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012397 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012398 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012399 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012400 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012401 // System process can do UI, and when they do we want to have
12402 // them trim their memory after the user leaves the UI. To
12403 // facilitate this, here we need to determine whether or not it
12404 // is currently showing UI.
12405 app.systemNoUi = true;
12406 if (app == TOP_APP) {
12407 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012408 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012409 } else if (activitiesSize > 0) {
12410 for (int j = 0; j < activitiesSize; j++) {
12411 final ActivityRecord r = app.activities.get(j);
12412 if (r.visible) {
12413 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012414 }
12415 if (r.app == app) {
12416 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012417 }
12418 }
12419 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012420 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012421 }
12422
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012423 app.keeping = false;
12424 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012425 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012426
The Android Open Source Project4df24232009-03-05 14:34:35 -080012427 // Determine the importance of the process, starting with most
12428 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012429 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012430 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012431 boolean foregroundActivities = false;
12432 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012433 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012434 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012435 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012436 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012437 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012438 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012439 foregroundActivities = true;
12440 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012441 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012442 } else if (app.instrumentationClass != null) {
12443 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012444 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012445 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012446 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012447 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012448 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012449 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012450 // counts as being in the foreground for OOM killer purposes.
12451 // It's placed in a sched group based on the nature of the
12452 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012453 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012454 schedGroup = (queue == mFgBroadcastQueue)
12455 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012456 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012457 } else if (app.executingServices.size() > 0) {
12458 // An app that is currently executing a service callback also
12459 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012460 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012461 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012462 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012463 } else {
12464 // Assume process is hidden (has activities); we will correct
12465 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012466 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012467 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012468 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012469 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012470 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012471
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012472 boolean hasStoppingActivities = false;
12473
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012474 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012475 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012476 for (int j = 0; j < activitiesSize; j++) {
12477 final ActivityRecord r = app.activities.get(j);
12478 if (r.visible) {
12479 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012480 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12481 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012482 app.adjType = "visible";
12483 }
12484 schedGroup = Process.THREAD_GROUP_DEFAULT;
12485 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012486 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012487 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012488 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012489 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012490 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12491 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012492 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012493 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012494 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012495 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012496 } else if (r.state == ActivityState.STOPPING) {
12497 // We will apply the actual adjustment later, because
12498 // we want to allow this process to immediately go through
12499 // any memory trimming that is in effect.
12500 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012501 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012502 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012503 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012504 if (r.app == app) {
12505 app.hasActivities = true;
12506 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012507 }
12508 }
12509
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012510 if (adj == hiddenAdj && !app.hasActivities) {
12511 // Whoops, this process is completely empty as far as we know
12512 // at this point.
12513 adj = emptyAdj;
12514 app.empty = true;
12515 app.adjType = "bg-empty";
12516 }
12517
Dianne Hackborn7d608422011-08-07 16:24:18 -070012518 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012519 if (app.foregroundServices) {
12520 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012521 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012522 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012523 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012524 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012525 } else if (app.forcingToForeground != null) {
12526 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012527 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012528 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012529 app.adjType = "force-foreground";
12530 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012531 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012532 }
12533 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012534
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012535 if (app.foregroundServices) {
12536 interesting = true;
12537 }
12538
Dianne Hackborn7d608422011-08-07 16:24:18 -070012539 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012540 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012541 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012542 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012543 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012544 app.adjType = "heavy";
12545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012546
Dianne Hackborn7d608422011-08-07 16:24:18 -070012547 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012548 // This process is hosting what we currently consider to be the
12549 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012550 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012551 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012552 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012553 app.adjType = "home";
12554 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012555
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012556 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12557 && app.activities.size() > 0) {
12558 // This was the previous process that showed UI to the user.
12559 // We want to try to keep it around more aggressively, to give
12560 // a good experience around switching between two apps.
12561 adj = ProcessList.PREVIOUS_APP_ADJ;
12562 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12563 app.hidden = false;
12564 app.adjType = "previous";
12565 }
12566
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012567 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12568 + " reason=" + app.adjType);
12569
The Android Open Source Project4df24232009-03-05 14:34:35 -080012570 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012571 // there are applications dependent on our services or providers, but
12572 // this gives us a baseline and makes sure we don't get into an
12573 // infinite recursion.
12574 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012575 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012576
Christopher Tate6fa95972009-06-05 18:43:55 -070012577 if (mBackupTarget != null && app == mBackupTarget.app) {
12578 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012579 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012580 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012581 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012582 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012583 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012584 }
12585 }
12586
Dianne Hackborn7d608422011-08-07 16:24:18 -070012587 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012588 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012589 final long now = SystemClock.uptimeMillis();
12590 // This process is more important if the top activity is
12591 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012592 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012593 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012594 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012595 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012596 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012597 // If this process has shown some UI, let it immediately
12598 // go to the LRU list because it may be pretty heavy with
12599 // UI stuff. We'll tag it with a label just to help
12600 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012601 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012602 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012603 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012604 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012605 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012606 // This service has seen some activity within
12607 // recent memory, so we will keep its process ahead
12608 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012609 if (adj > ProcessList.SERVICE_ADJ) {
12610 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012611 app.adjType = "started-services";
12612 app.hidden = false;
12613 }
12614 }
12615 // If we have let the service slide into the background
12616 // state, still have some text describing what it is doing
12617 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012618 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012619 app.adjType = "started-bg-services";
12620 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012621 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012622 // Don't kill this process because it is doing work; it
12623 // has said it is doing work.
12624 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012625 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012626 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012627 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012628 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012630 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012631 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012632 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012633 // XXX should compute this based on the max of
12634 // all connected clients.
12635 ConnectionRecord cr = clist.get(i);
12636 if (cr.binding.client == app) {
12637 // Binding to ourself is not interesting.
12638 continue;
12639 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012640 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012641 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012642 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012643 int myHiddenAdj = hiddenAdj;
12644 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012645 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012646 myHiddenAdj = client.hiddenAdj;
12647 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012648 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012649 }
12650 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012651 int myEmptyAdj = emptyAdj;
12652 if (myEmptyAdj > client.emptyAdj) {
12653 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12654 myEmptyAdj = client.emptyAdj;
12655 } else {
12656 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12657 }
12658 }
12659 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12660 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012661 String adjType = null;
12662 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12663 // Not doing bind OOM management, so treat
12664 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012665 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012666 // If this process has shown some UI, let it immediately
12667 // go to the LRU list because it may be pretty heavy with
12668 // UI stuff. We'll tag it with a label just to help
12669 // debug and understand what is going on.
12670 if (adj > clientAdj) {
12671 adjType = "bound-bg-ui-services";
12672 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012673 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012674 clientAdj = adj;
12675 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012676 if (now >= (s.lastActivity
12677 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012678 // This service has not seen activity within
12679 // recent memory, so allow it to drop to the
12680 // LRU list if there is no other reason to keep
12681 // it around. We'll also tag it with a label just
12682 // to help debug and undertand what is going on.
12683 if (adj > clientAdj) {
12684 adjType = "bound-bg-services";
12685 }
12686 clientAdj = adj;
12687 }
12688 }
12689 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012690 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012691 // If this process has recently shown UI, and
12692 // the process that is binding to it is less
12693 // important than being visible, then we don't
12694 // care about the binding as much as we care
12695 // about letting this process get into the LRU
12696 // list to be killed and restarted if needed for
12697 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012698 if (app.hasShownUi && app != mHomeProcess
12699 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012700 adjType = "bound-bg-ui-services";
12701 } else {
12702 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12703 |Context.BIND_IMPORTANT)) != 0) {
12704 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012705 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12706 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12707 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12708 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12709 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012710 adj = clientAdj;
12711 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012712 app.pendingUiClean = true;
12713 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12714 adj = ProcessList.VISIBLE_APP_ADJ;
12715 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012716 }
12717 if (!client.hidden) {
12718 app.hidden = false;
12719 }
12720 if (client.keeping) {
12721 app.keeping = true;
12722 }
12723 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012724 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012725 }
12726 if (adjType != null) {
12727 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012728 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12729 .REASON_SERVICE_IN_USE;
12730 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012731 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012732 app.adjTarget = s.name;
12733 }
12734 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12735 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12736 schedGroup = Process.THREAD_GROUP_DEFAULT;
12737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012738 }
12739 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012740 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12741 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012742 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012743 (a.visible || a.state == ActivityState.RESUMED
12744 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012745 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012746 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12747 schedGroup = Process.THREAD_GROUP_DEFAULT;
12748 }
12749 app.hidden = false;
12750 app.adjType = "service";
12751 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12752 .REASON_SERVICE_IN_USE;
12753 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012754 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012755 app.adjTarget = s.name;
12756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012758 }
12759 }
12760 }
12761 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012762
Dianne Hackborn287952c2010-09-22 22:34:31 -070012763 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012764 // would like to avoid killing it unless it would prevent the current
12765 // application from running. By default we put the process in
12766 // with the rest of the background processes; as we scan through
12767 // its services we may bump it up from there.
12768 if (adj > hiddenAdj) {
12769 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012770 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012771 app.adjType = "bg-services";
12772 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012773 }
12774
Dianne Hackborn7d608422011-08-07 16:24:18 -070012775 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012776 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012777 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012778 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012779 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012780 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012781 for (int i = cpr.connections.size()-1;
12782 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12783 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12784 i--) {
12785 ContentProviderConnection conn = cpr.connections.get(i);
12786 ProcessRecord client = conn.client;
12787 if (client == app) {
12788 // Being our own client is not interesting.
12789 continue;
12790 }
12791 int myHiddenAdj = hiddenAdj;
12792 if (myHiddenAdj > client.hiddenAdj) {
12793 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12794 myHiddenAdj = client.hiddenAdj;
12795 } else {
12796 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012797 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012798 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012799 int myEmptyAdj = emptyAdj;
12800 if (myEmptyAdj > client.emptyAdj) {
12801 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12802 myEmptyAdj = client.emptyAdj;
12803 } else {
12804 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12805 }
12806 }
12807 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12808 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012809 if (adj > clientAdj) {
12810 if (app.hasShownUi && app != mHomeProcess
12811 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12812 app.adjType = "bg-ui-provider";
12813 } else {
12814 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12815 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12816 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012817 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012818 if (!client.hidden) {
12819 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012820 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012821 if (client.keeping) {
12822 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012823 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012824 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12825 .REASON_PROVIDER_IN_USE;
12826 app.adjSource = client;
12827 app.adjSourceOom = clientAdj;
12828 app.adjTarget = cpr.name;
12829 }
12830 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12831 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012832 }
12833 }
12834 // If the provider has external (non-framework) process
12835 // dependencies, ensure that its adjustment is at least
12836 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012837 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012838 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12839 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012840 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012841 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012842 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012843 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012844 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012845 }
12846 }
12847 }
12848 }
12849
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012850 if (adj == ProcessList.SERVICE_ADJ) {
12851 if (doingAll) {
12852 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12853 mNewNumServiceProcs++;
12854 }
12855 if (app.serviceb) {
12856 adj = ProcessList.SERVICE_B_ADJ;
12857 }
12858 } else {
12859 app.serviceb = false;
12860 }
12861
12862 app.nonStoppingAdj = adj;
12863
12864 if (hasStoppingActivities) {
12865 // Only upgrade adjustment.
12866 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12867 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12868 app.adjType = "stopping";
12869 }
12870 }
12871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012872 app.curRawAdj = adj;
12873
Joe Onorato8a9b2202010-02-26 18:56:32 -080012874 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012875 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12876 if (adj > app.maxAdj) {
12877 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012878 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012879 schedGroup = Process.THREAD_GROUP_DEFAULT;
12880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012881 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012882 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012883 app.keeping = true;
12884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012885
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012886 if (app.hasAboveClient) {
12887 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12888 // then we need to drop its adjustment to be lower than the service's
12889 // in order to honor the request. We want to drop it by one adjustment
12890 // level... but there is special meaning applied to various levels so
12891 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012892 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012893 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012894 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12895 adj = ProcessList.VISIBLE_APP_ADJ;
12896 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12897 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12898 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12899 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012900 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012901 adj++;
12902 }
12903 }
12904
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012905 int importance = app.memImportance;
12906 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12907 app.curAdj = adj;
12908 app.curSchedGroup = schedGroup;
12909 if (!interesting) {
12910 // For this reporting, if there is not something explicitly
12911 // interesting in this process then we will push it to the
12912 // background importance.
12913 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12914 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12915 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12916 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12917 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12918 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12919 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12920 } else if (adj >= ProcessList.SERVICE_ADJ) {
12921 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12922 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12923 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12924 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12925 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
12926 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
12927 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
12928 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
12929 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
12930 } else {
12931 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
12932 }
12933 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012934
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012935 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
12936 if (foregroundActivities != app.foregroundActivities) {
12937 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
12938 }
12939 if (changes != 0) {
12940 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
12941 app.memImportance = importance;
12942 app.foregroundActivities = foregroundActivities;
12943 int i = mPendingProcessChanges.size()-1;
12944 ProcessChangeItem item = null;
12945 while (i >= 0) {
12946 item = mPendingProcessChanges.get(i);
12947 if (item.pid == app.pid) {
12948 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
12949 break;
12950 }
12951 i--;
12952 }
12953 if (i < 0) {
12954 // No existing item in pending changes; need a new one.
12955 final int NA = mAvailProcessChanges.size();
12956 if (NA > 0) {
12957 item = mAvailProcessChanges.remove(NA-1);
12958 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
12959 } else {
12960 item = new ProcessChangeItem();
12961 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
12962 }
12963 item.changes = 0;
12964 item.pid = app.pid;
12965 item.uid = app.info.uid;
12966 if (mPendingProcessChanges.size() == 0) {
12967 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
12968 "*** Enqueueing dispatch processes changed!");
12969 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
12970 }
12971 mPendingProcessChanges.add(item);
12972 }
12973 item.changes |= changes;
12974 item.importance = importance;
12975 item.foregroundActivities = foregroundActivities;
12976 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
12977 + Integer.toHexString(System.identityHashCode(item))
12978 + " " + app.toShortString() + ": changes=" + item.changes
12979 + " importance=" + item.importance
12980 + " foreground=" + item.foregroundActivities
12981 + " type=" + app.adjType + " source=" + app.adjSource
12982 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012983 }
12984
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012985 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012986 }
12987
12988 /**
12989 * Ask a given process to GC right now.
12990 */
12991 final void performAppGcLocked(ProcessRecord app) {
12992 try {
12993 app.lastRequestedGc = SystemClock.uptimeMillis();
12994 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012995 if (app.reportLowMemory) {
12996 app.reportLowMemory = false;
12997 app.thread.scheduleLowMemory();
12998 } else {
12999 app.thread.processInBackground();
13000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013001 }
13002 } catch (Exception e) {
13003 // whatever.
13004 }
13005 }
13006
13007 /**
13008 * Returns true if things are idle enough to perform GCs.
13009 */
Josh Bartel7f208742010-02-25 11:01:44 -060013010 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013011 boolean processingBroadcasts = false;
13012 for (BroadcastQueue q : mBroadcastQueues) {
13013 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13014 processingBroadcasts = true;
13015 }
13016 }
13017 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013018 && (mSleeping || (mMainStack.mResumedActivity != null &&
13019 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013020 }
13021
13022 /**
13023 * Perform GCs on all processes that are waiting for it, but only
13024 * if things are idle.
13025 */
13026 final void performAppGcsLocked() {
13027 final int N = mProcessesToGc.size();
13028 if (N <= 0) {
13029 return;
13030 }
Josh Bartel7f208742010-02-25 11:01:44 -060013031 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013032 while (mProcessesToGc.size() > 0) {
13033 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013034 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013035 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13036 <= SystemClock.uptimeMillis()) {
13037 // To avoid spamming the system, we will GC processes one
13038 // at a time, waiting a few seconds between each.
13039 performAppGcLocked(proc);
13040 scheduleAppGcsLocked();
13041 return;
13042 } else {
13043 // It hasn't been long enough since we last GCed this
13044 // process... put it in the list to wait for its time.
13045 addProcessToGcListLocked(proc);
13046 break;
13047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013048 }
13049 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013050
13051 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013052 }
13053 }
13054
13055 /**
13056 * If all looks good, perform GCs on all processes waiting for them.
13057 */
13058 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013059 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013060 performAppGcsLocked();
13061 return;
13062 }
13063 // Still not idle, wait some more.
13064 scheduleAppGcsLocked();
13065 }
13066
13067 /**
13068 * Schedule the execution of all pending app GCs.
13069 */
13070 final void scheduleAppGcsLocked() {
13071 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013072
13073 if (mProcessesToGc.size() > 0) {
13074 // Schedule a GC for the time to the next process.
13075 ProcessRecord proc = mProcessesToGc.get(0);
13076 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13077
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013078 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013079 long now = SystemClock.uptimeMillis();
13080 if (when < (now+GC_TIMEOUT)) {
13081 when = now + GC_TIMEOUT;
13082 }
13083 mHandler.sendMessageAtTime(msg, when);
13084 }
13085 }
13086
13087 /**
13088 * Add a process to the array of processes waiting to be GCed. Keeps the
13089 * list in sorted order by the last GC time. The process can't already be
13090 * on the list.
13091 */
13092 final void addProcessToGcListLocked(ProcessRecord proc) {
13093 boolean added = false;
13094 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13095 if (mProcessesToGc.get(i).lastRequestedGc <
13096 proc.lastRequestedGc) {
13097 added = true;
13098 mProcessesToGc.add(i+1, proc);
13099 break;
13100 }
13101 }
13102 if (!added) {
13103 mProcessesToGc.add(0, proc);
13104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013105 }
13106
13107 /**
13108 * Set up to ask a process to GC itself. This will either do it
13109 * immediately, or put it on the list of processes to gc the next
13110 * time things are idle.
13111 */
13112 final void scheduleAppGcLocked(ProcessRecord app) {
13113 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013114 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013115 return;
13116 }
13117 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013118 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013119 scheduleAppGcsLocked();
13120 }
13121 }
13122
Dianne Hackborn287952c2010-09-22 22:34:31 -070013123 final void checkExcessivePowerUsageLocked(boolean doKills) {
13124 updateCpuStatsNow();
13125
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013126 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013127 boolean doWakeKills = doKills;
13128 boolean doCpuKills = doKills;
13129 if (mLastPowerCheckRealtime == 0) {
13130 doWakeKills = false;
13131 }
13132 if (mLastPowerCheckUptime == 0) {
13133 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013134 }
13135 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013136 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013137 }
13138 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013139 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13140 final long curUptime = SystemClock.uptimeMillis();
13141 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13142 mLastPowerCheckRealtime = curRealtime;
13143 mLastPowerCheckUptime = curUptime;
13144 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13145 doWakeKills = false;
13146 }
13147 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13148 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013149 }
13150 int i = mLruProcesses.size();
13151 while (i > 0) {
13152 i--;
13153 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013154 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013155 long wtime;
13156 synchronized (stats) {
13157 wtime = stats.getProcessWakeTime(app.info.uid,
13158 app.pid, curRealtime);
13159 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013160 long wtimeUsed = wtime - app.lastWakeTime;
13161 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13162 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013163 StringBuilder sb = new StringBuilder(128);
13164 sb.append("Wake for ");
13165 app.toShortString(sb);
13166 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013167 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013168 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013169 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013170 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013171 sb.append((wtimeUsed*100)/realtimeSince);
13172 sb.append("%)");
13173 Slog.i(TAG, sb.toString());
13174 sb.setLength(0);
13175 sb.append("CPU for ");
13176 app.toShortString(sb);
13177 sb.append(": over ");
13178 TimeUtils.formatDuration(uptimeSince, sb);
13179 sb.append(" used ");
13180 TimeUtils.formatDuration(cputimeUsed, sb);
13181 sb.append(" (");
13182 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013183 sb.append("%)");
13184 Slog.i(TAG, sb.toString());
13185 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013186 // If a process has held a wake lock for more
13187 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013188 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013189 if (doWakeKills && realtimeSince > 0
13190 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13191 synchronized (stats) {
13192 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13193 realtimeSince, wtimeUsed);
13194 }
13195 Slog.w(TAG, "Excessive wake lock in " + app.processName
13196 + " (pid " + app.pid + "): held " + wtimeUsed
13197 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013198 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13199 app.processName, app.setAdj, "excessive wake lock");
13200 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013201 } else if (doCpuKills && uptimeSince > 0
13202 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13203 synchronized (stats) {
13204 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13205 uptimeSince, cputimeUsed);
13206 }
13207 Slog.w(TAG, "Excessive CPU in " + app.processName
13208 + " (pid " + app.pid + "): used " + cputimeUsed
13209 + " during " + uptimeSince);
13210 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13211 app.processName, app.setAdj, "excessive cpu");
13212 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013213 } else {
13214 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013215 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013216 }
13217 }
13218 }
13219 }
13220
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013221 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
13222 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013223 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013224 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013225
13226 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013227 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013228 }
13229
Dianne Hackborn287952c2010-09-22 22:34:31 -070013230 final boolean wasKeeping = app.keeping;
13231
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013232 boolean success = true;
13233
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013234 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013235
Jeff Brown10e89712011-07-08 18:52:57 -070013236 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013237 if (wasKeeping && !app.keeping) {
13238 // This app is no longer something we want to keep. Note
13239 // its current wake lock time to later know to kill it if
13240 // it is not behaving well.
13241 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13242 synchronized (stats) {
13243 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13244 app.pid, SystemClock.elapsedRealtime());
13245 }
13246 app.lastCpuTime = app.curCpuTime;
13247 }
13248
13249 app.setRawAdj = app.curRawAdj;
13250 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013251
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013252 if (app.curAdj != app.setAdj) {
13253 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013254 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013255 TAG, "Set " + app.pid + " " + app.processName +
13256 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013257 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013258 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013259 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013260 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013261 }
13262 }
13263 if (app.setSchedGroup != app.curSchedGroup) {
13264 app.setSchedGroup = app.curSchedGroup;
13265 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13266 "Setting process group of " + app.processName
13267 + " to " + app.curSchedGroup);
13268 if (app.waitingToKill != null &&
13269 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13270 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13271 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13272 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013273 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013274 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013275 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013276 } else {
13277 if (true) {
13278 long oldId = Binder.clearCallingIdentity();
13279 try {
13280 Process.setProcessGroup(app.pid, app.curSchedGroup);
13281 } catch (Exception e) {
13282 Slog.w(TAG, "Failed setting process group of " + app.pid
13283 + " to " + app.curSchedGroup);
13284 e.printStackTrace();
13285 } finally {
13286 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013287 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013288 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013289 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013290 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013291 app.thread.setSchedulingGroup(app.curSchedGroup);
13292 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013293 }
13294 }
13295 }
13296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013297 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013298 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013299 }
13300
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013301 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013302 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013303 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013304 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013305 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013306 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013307 }
13308 }
13309 return resumedActivity;
13310 }
13311
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013312 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013313 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013314 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13315 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013316 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13317 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013318
13319 mAdjSeq++;
13320
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013321 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
13322 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013323 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13324 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013325 if (nowHidden != wasHidden) {
13326 // Changed to/from hidden state, so apps after it in the LRU
13327 // list may also be changed.
13328 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013329 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013330 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013331 }
13332
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013333 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013334 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013335 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13336
13337 if (false) {
13338 RuntimeException e = new RuntimeException();
13339 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013340 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013341 }
13342
13343 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013344 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013345
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013346 // Let's determine how many processes we have running vs.
13347 // how many slots we have for background processes; we may want
13348 // to put multiple processes in a slot of there are enough of
13349 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013350 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13351 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
13352 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
13353 if (emptyFactor < 1) emptyFactor = 1;
13354 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13355 if (hiddenFactor < 1) hiddenFactor = 1;
13356 int stepHidden = 0;
13357 int stepEmpty = 0;
13358 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
13359 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013360 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013361 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013362 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013363
13364 mNumNonHiddenProcs = 0;
13365 mNumHiddenProcs = 0;
13366
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013367 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013368 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013369 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013370 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013371 int nextHiddenAdj = curHiddenAdj+1;
13372 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13373 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013374 while (i > 0) {
13375 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013376 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013377 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013378 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013379 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013380 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13381 // This process was assigned as a hidden process... step the
13382 // hidden level.
13383 mNumHiddenProcs++;
13384 if (curHiddenAdj != nextHiddenAdj) {
13385 stepHidden++;
13386 if (stepHidden >= hiddenFactor) {
13387 stepHidden = 0;
13388 curHiddenAdj = nextHiddenAdj;
13389 nextHiddenAdj += 2;
13390 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13391 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13392 }
13393 }
13394 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013395 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013396 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013397 Slog.i(TAG, "No longer want " + app.processName
13398 + " (pid " + app.pid + "): hidden #" + numHidden);
13399 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13400 app.processName, app.setAdj, "too many background");
13401 app.killedBackground = true;
13402 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013403 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013404 } else {
13405 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13406 // This process was assigned as an empty process... step the
13407 // empty level.
13408 if (curEmptyAdj != nextEmptyAdj) {
13409 stepEmpty++;
13410 if (stepEmpty >= emptyFactor) {
13411 stepEmpty = 0;
13412 curEmptyAdj = nextEmptyAdj;
13413 nextEmptyAdj += 2;
13414 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13415 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13416 }
13417 }
13418 }
13419 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13420 mNumNonHiddenProcs++;
13421 }
13422 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13423 numEmpty++;
13424 if (numEmpty > emptyProcessLimit) {
13425 Slog.i(TAG, "No longer want " + app.processName
13426 + " (pid " + app.pid + "): empty #" + numEmpty);
13427 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13428 app.processName, app.setAdj, "too many background");
13429 app.killedBackground = true;
13430 Process.killProcessQuiet(app.pid);
13431 }
13432 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013433 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013434 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013435 // If this is an isolated process, and there are no
13436 // services running in it, then the process is no longer
13437 // needed. We agressively kill these because we can by
13438 // definition not re-use the same process again, and it is
13439 // good to avoid having whatever code was running in them
13440 // left sitting around after no longer needed.
13441 Slog.i(TAG, "Isolated process " + app.processName
13442 + " (pid " + app.pid + ") no longer needed");
13443 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13444 app.processName, app.setAdj, "isolated not needed");
13445 app.killedBackground = true;
13446 Process.killProcessQuiet(app.pid);
13447 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013448 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13449 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13450 && !app.killedBackground) {
13451 numTrimming++;
13452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013453 }
13454 }
13455
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013456 mNumServiceProcs = mNewNumServiceProcs;
13457
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013458 // Now determine the memory trimming level of background processes.
13459 // Unfortunately we need to start at the back of the list to do this
13460 // properly. We only do this if the number of background apps we
13461 // are managing to keep around is less than half the maximum we desire;
13462 // if we are keeping a good number around, we'll let them use whatever
13463 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013464 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13465 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13466 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013467 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013468 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013469 int minFactor = 2;
13470 if (mHomeProcess != null) minFactor++;
13471 if (mPreviousProcess != null) minFactor++;
13472 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013473 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013474 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013475 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013476 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013477 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013478 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13479 } else {
13480 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13481 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013482 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013483 for (i=0; i<N; i++) {
13484 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013485 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13486 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013487 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013488 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13489 try {
13490 app.thread.scheduleTrimMemory(curLevel);
13491 } catch (RemoteException e) {
13492 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013493 if (false) {
13494 // For now we won't do this; our memory trimming seems
13495 // to be good enough at this point that destroying
13496 // activities causes more harm than good.
13497 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13498 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013499 // Need to do this on its own message because the stack may not
13500 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013501 // For these apps we will also finish their activities
13502 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013503 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013504 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013505 }
13506 }
13507 app.trimMemoryLevel = curLevel;
13508 step++;
13509 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013510 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013511 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013512 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13513 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013514 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013515 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13516 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013517 break;
13518 }
13519 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013520 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013521 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013522 && app.thread != null) {
13523 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013524 app.thread.scheduleTrimMemory(
13525 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013526 } catch (RemoteException e) {
13527 }
13528 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013529 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013530 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013531 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013532 && app.pendingUiClean) {
13533 // If this application is now in the background and it
13534 // had done UI, then give it the special trim level to
13535 // have it free UI resources.
13536 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13537 if (app.trimMemoryLevel < level && app.thread != null) {
13538 try {
13539 app.thread.scheduleTrimMemory(level);
13540 } catch (RemoteException e) {
13541 }
13542 }
13543 app.pendingUiClean = false;
13544 }
13545 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013546 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013547 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013548 } catch (RemoteException e) {
13549 }
13550 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013551 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013552 }
13553 }
13554 } else {
13555 final int N = mLruProcesses.size();
13556 for (i=0; i<N; i++) {
13557 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013558 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013559 && app.pendingUiClean) {
13560 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13561 && app.thread != null) {
13562 try {
13563 app.thread.scheduleTrimMemory(
13564 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13565 } catch (RemoteException e) {
13566 }
13567 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013568 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013569 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013570 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013571 }
13572 }
13573
13574 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013575 // Need to do this on its own message because the stack may not
13576 // be in a consistent state at this point.
13577 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013579 }
13580
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013581 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013582 synchronized (this) {
13583 int i;
13584
13585 // First remove any unused application processes whose package
13586 // has been removed.
13587 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13588 final ProcessRecord app = mRemovedProcesses.get(i);
13589 if (app.activities.size() == 0
13590 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013591 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013592 TAG, "Exiting empty application process "
13593 + app.processName + " ("
13594 + (app.thread != null ? app.thread.asBinder() : null)
13595 + ")\n");
13596 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013597 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13598 app.processName, app.setAdj, "empty");
13599 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013600 } else {
13601 try {
13602 app.thread.scheduleExit();
13603 } catch (Exception e) {
13604 // Ignore exceptions.
13605 }
13606 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013607 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013608 mRemovedProcesses.remove(i);
13609
13610 if (app.persistent) {
13611 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013612 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013613 }
13614 }
13615 }
13616 }
13617
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013618 // Now update the oom adj for all processes.
13619 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013620 }
13621 }
13622
13623 /** This method sends the specified signal to each of the persistent apps */
13624 public void signalPersistentProcesses(int sig) throws RemoteException {
13625 if (sig != Process.SIGNAL_USR1) {
13626 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13627 }
13628
13629 synchronized (this) {
13630 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13631 != PackageManager.PERMISSION_GRANTED) {
13632 throw new SecurityException("Requires permission "
13633 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13634 }
13635
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013636 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13637 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013638 if (r.thread != null && r.persistent) {
13639 Process.sendSignal(r.pid, sig);
13640 }
13641 }
13642 }
13643 }
13644
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013645 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13646 if (proc == null || proc == mProfileProc) {
13647 proc = mProfileProc;
13648 path = mProfileFile;
13649 profileType = mProfileType;
13650 clearProfilerLocked();
13651 }
13652 if (proc == null) {
13653 return;
13654 }
13655 try {
13656 proc.thread.profilerControl(false, path, null, profileType);
13657 } catch (RemoteException e) {
13658 throw new IllegalStateException("Process disappeared");
13659 }
13660 }
13661
13662 private void clearProfilerLocked() {
13663 if (mProfileFd != null) {
13664 try {
13665 mProfileFd.close();
13666 } catch (IOException e) {
13667 }
13668 }
13669 mProfileApp = null;
13670 mProfileProc = null;
13671 mProfileFile = null;
13672 mProfileType = 0;
13673 mAutoStopProfiler = false;
13674 }
13675
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013676 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013677 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013678
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013679 try {
13680 synchronized (this) {
13681 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13682 // its own permission.
13683 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13684 != PackageManager.PERMISSION_GRANTED) {
13685 throw new SecurityException("Requires permission "
13686 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013687 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013688
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013689 if (start && fd == null) {
13690 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013691 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013692
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013693 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013694 if (process != null) {
13695 try {
13696 int pid = Integer.parseInt(process);
13697 synchronized (mPidsSelfLocked) {
13698 proc = mPidsSelfLocked.get(pid);
13699 }
13700 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013701 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013702
13703 if (proc == null) {
13704 HashMap<String, SparseArray<ProcessRecord>> all
13705 = mProcessNames.getMap();
13706 SparseArray<ProcessRecord> procs = all.get(process);
13707 if (procs != null && procs.size() > 0) {
13708 proc = procs.valueAt(0);
13709 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013710 }
13711 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013712
13713 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013714 throw new IllegalArgumentException("Unknown process: " + process);
13715 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013716
13717 if (start) {
13718 stopProfilerLocked(null, null, 0);
13719 setProfileApp(proc.info, proc.processName, path, fd, false);
13720 mProfileProc = proc;
13721 mProfileType = profileType;
13722 try {
13723 fd = fd.dup();
13724 } catch (IOException e) {
13725 fd = null;
13726 }
13727 proc.thread.profilerControl(start, path, fd, profileType);
13728 fd = null;
13729 mProfileFd = null;
13730 } else {
13731 stopProfilerLocked(proc, path, profileType);
13732 if (fd != null) {
13733 try {
13734 fd.close();
13735 } catch (IOException e) {
13736 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013737 }
13738 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013739
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013740 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013741 }
13742 } catch (RemoteException e) {
13743 throw new IllegalStateException("Process disappeared");
13744 } finally {
13745 if (fd != null) {
13746 try {
13747 fd.close();
13748 } catch (IOException e) {
13749 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013750 }
13751 }
13752 }
Andy McFadden824c5102010-07-09 16:26:57 -070013753
13754 public boolean dumpHeap(String process, boolean managed,
13755 String path, ParcelFileDescriptor fd) throws RemoteException {
13756
13757 try {
13758 synchronized (this) {
13759 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13760 // its own permission (same as profileControl).
13761 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13762 != PackageManager.PERMISSION_GRANTED) {
13763 throw new SecurityException("Requires permission "
13764 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13765 }
13766
13767 if (fd == null) {
13768 throw new IllegalArgumentException("null fd");
13769 }
13770
13771 ProcessRecord proc = null;
13772 try {
13773 int pid = Integer.parseInt(process);
13774 synchronized (mPidsSelfLocked) {
13775 proc = mPidsSelfLocked.get(pid);
13776 }
13777 } catch (NumberFormatException e) {
13778 }
13779
13780 if (proc == null) {
13781 HashMap<String, SparseArray<ProcessRecord>> all
13782 = mProcessNames.getMap();
13783 SparseArray<ProcessRecord> procs = all.get(process);
13784 if (procs != null && procs.size() > 0) {
13785 proc = procs.valueAt(0);
13786 }
13787 }
13788
13789 if (proc == null || proc.thread == null) {
13790 throw new IllegalArgumentException("Unknown process: " + process);
13791 }
13792
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013793 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13794 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013795 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13796 throw new SecurityException("Process not debuggable: " + proc);
13797 }
13798 }
13799
13800 proc.thread.dumpHeap(managed, path, fd);
13801 fd = null;
13802 return true;
13803 }
13804 } catch (RemoteException e) {
13805 throw new IllegalStateException("Process disappeared");
13806 } finally {
13807 if (fd != null) {
13808 try {
13809 fd.close();
13810 } catch (IOException e) {
13811 }
13812 }
13813 }
13814 }
13815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013816 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13817 public void monitor() {
13818 synchronized (this) { }
13819 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013820
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013821 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013822 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13823 ProcessRecord processRecord = mLruProcesses.get(i);
13824 try {
13825 if (processRecord.thread != null) {
13826 processRecord.thread.setCoreSettings(settings);
13827 }
13828 } catch (RemoteException re) {
13829 /* ignore */
13830 }
13831 }
13832 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013833
13834 // Multi-user methods
13835
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013836 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070013837 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013838 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13839 != PackageManager.PERMISSION_GRANTED) {
13840 String msg = "Permission Denial: switchUser() from pid="
13841 + Binder.getCallingPid()
13842 + ", uid=" + Binder.getCallingUid()
13843 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13844 Slog.w(TAG, msg);
13845 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013846 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013847 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013848 if (mCurrentUserId == userId) {
13849 return true;
13850 }
13851
13852 // If the user we are switching to is not currently started, then
13853 // we need to start it now.
13854 if (mStartedUsers.get(userId) == null) {
13855 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Amith Yamasani742a6712011-05-04 14:49:28 -070013856 }
13857
13858 mCurrentUserId = userId;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070013859 Integer userIdInt = Integer.valueOf(userId);
13860 mUserLru.remove(userIdInt);
13861 mUserLru.add(userIdInt);
Amith Yamasani742a6712011-05-04 14:49:28 -070013862 boolean haveActivities = mMainStack.switchUser(userId);
13863 if (!haveActivities) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013864 startHomeActivityLocked(userId, mStartedUsers.get(userId));
Amith Yamasani742a6712011-05-04 14:49:28 -070013865 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013866 }
Amith Yamasani13593602012-03-22 16:16:17 -070013867
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013868 long ident = Binder.clearCallingIdentity();
13869 try {
13870 // Inform of user switch
13871 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
13872 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070013873 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
13874 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013875 } finally {
13876 Binder.restoreCallingIdentity(ident);
13877 }
Amith Yamasani13593602012-03-22 16:16:17 -070013878
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013879 return true;
13880 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013881
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013882 void finishUserSwitch(UserStartedState uss) {
13883 synchronized (this) {
13884 if (uss.mState == UserStartedState.STATE_BOOTING
13885 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
13886 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070013887 final int userId = uss.mHandle.getIdentifier();
13888 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
13889 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
13890 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013891 null, null, 0, null, null,
13892 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070013893 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013894 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013895 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013896 }
13897
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013898 @Override
13899 public int stopUser(final int userId, final IStopUserCallback callback) {
13900 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13901 != PackageManager.PERMISSION_GRANTED) {
13902 String msg = "Permission Denial: switchUser() from pid="
13903 + Binder.getCallingPid()
13904 + ", uid=" + Binder.getCallingUid()
13905 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13906 Slog.w(TAG, msg);
13907 throw new SecurityException(msg);
13908 }
13909 if (userId <= 0) {
13910 throw new IllegalArgumentException("Can't stop primary user " + userId);
13911 }
Amith Yamasani13593602012-03-22 16:16:17 -070013912 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013913 if (mCurrentUserId == userId) {
13914 return ActivityManager.USER_OP_IS_CURRENT;
13915 }
13916
13917 final UserStartedState uss = mStartedUsers.get(userId);
13918 if (uss == null) {
13919 // User is not started, nothing to do... but we do need to
13920 // callback if requested.
13921 if (callback != null) {
13922 mHandler.post(new Runnable() {
13923 @Override
13924 public void run() {
13925 try {
13926 callback.userStopped(userId);
13927 } catch (RemoteException e) {
13928 }
13929 }
13930 });
13931 }
13932 return ActivityManager.USER_OP_SUCCESS;
13933 }
13934
13935 if (callback != null) {
13936 uss.mStopCallbacks.add(callback);
13937 }
13938
13939 if (uss.mState != UserStartedState.STATE_STOPPING) {
13940 uss.mState = UserStartedState.STATE_STOPPING;
13941
13942 long ident = Binder.clearCallingIdentity();
13943 try {
13944 // Inform of user switch
13945 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
13946 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
13947 @Override
13948 public void performReceive(Intent intent, int resultCode, String data,
Dianne Hackborn20e80982012-08-31 19:00:44 -070013949 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013950 finishUserStop(uss);
13951 }
13952 };
13953 broadcastIntentLocked(null, null, intent,
13954 null, resultReceiver, 0, null, null, null,
13955 true, false, MY_PID, Process.SYSTEM_UID, userId);
13956 } finally {
13957 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070013958 }
13959 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013960 }
Amith Yamasani13593602012-03-22 16:16:17 -070013961
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013962 return ActivityManager.USER_OP_SUCCESS;
13963 }
13964
13965 void finishUserStop(UserStartedState uss) {
13966 final int userId = uss.mHandle.getIdentifier();
13967 boolean stopped;
13968 ArrayList<IStopUserCallback> callbacks;
13969 synchronized (this) {
13970 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
13971 if (uss.mState != UserStartedState.STATE_STOPPING
13972 || mStartedUsers.get(userId) != uss) {
13973 stopped = false;
13974 } else {
13975 stopped = true;
13976 // User can no longer run.
13977 mStartedUsers.remove(userId);
13978
13979 // Clean up all state and processes associated with the user.
13980 // Kill all the processes for the user.
13981 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070013982 }
13983 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013984
13985 for (int i=0; i<callbacks.size(); i++) {
13986 try {
13987 if (stopped) callbacks.get(i).userStopped(userId);
13988 else callbacks.get(i).userStopAborted(userId);
13989 } catch (RemoteException e) {
13990 }
13991 }
13992 }
13993
13994 @Override
13995 public UserInfo getCurrentUser() {
13996 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13997 != PackageManager.PERMISSION_GRANTED) {
13998 String msg = "Permission Denial: getCurrentUser() from pid="
13999 + Binder.getCallingPid()
14000 + ", uid=" + Binder.getCallingUid()
14001 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14002 Slog.w(TAG, msg);
14003 throw new SecurityException(msg);
14004 }
14005 synchronized (this) {
14006 return getUserManager().getUserInfo(mCurrentUserId);
14007 }
Amith Yamasani13593602012-03-22 16:16:17 -070014008 }
14009
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014010 @Override
14011 public boolean isUserRunning(int userId) {
14012 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14013 != PackageManager.PERMISSION_GRANTED) {
14014 String msg = "Permission Denial: isUserRunning() from pid="
14015 + Binder.getCallingPid()
14016 + ", uid=" + Binder.getCallingUid()
14017 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14018 Slog.w(TAG, msg);
14019 throw new SecurityException(msg);
14020 }
14021 synchronized (this) {
14022 UserStartedState state = mStartedUsers.get(userId);
14023 return state != null && state.mState != UserStartedState.STATE_STOPPING;
14024 }
14025 }
14026
Amith Yamasani742a6712011-05-04 14:49:28 -070014027 private boolean userExists(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -070014028 UserInfo user = getUserManager().getUserInfo(userId);
14029 return user != null;
14030 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014031
Amith Yamasani258848d2012-08-10 17:06:33 -070014032 UserManager getUserManager() {
14033 if (mUserManager == null) {
14034 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
14035 }
14036 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014037 }
14038
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014039 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014040 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014041
14042 throw new SecurityException("Caller uid=" + uid
14043 + " is not privileged to communicate with user=" + userId);
14044 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014045
14046 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014047 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014048 }
14049
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014050 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014051 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014052 ApplicationInfo newInfo = new ApplicationInfo(info);
14053 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014054 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14055 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014056 return newInfo;
14057 }
14058
14059 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014060 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014061 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014062 return aInfo;
14063 }
14064
14065 ActivityInfo info = new ActivityInfo(aInfo);
14066 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14067 return info;
14068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014069}