blob: 90e8d73e66f99232a37289094864aa08bf35842a [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 =
Amith Yamasani259d5e52012-08-31 15:11:01 -07002153 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002154 if (aInfo != null) {
2155 intent.setComponent(new ComponentName(
2156 aInfo.applicationInfo.packageName, aInfo.name));
2157 // Don't do this if the home app is currently being
2158 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002159 aInfo = new ActivityInfo(aInfo);
2160 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002161 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2162 aInfo.applicationInfo.uid);
2163 if (app == null || app.instrumentationClass == null) {
2164 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002165 mMainStack.startActivityLocked(null, intent, null, aInfo,
2166 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002167 }
2168 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002169 if (startingUser != null) {
2170 mMainStack.addStartingUserLocked(startingUser);
2171 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002172
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002173 return true;
2174 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002175
Amith Yamasani259d5e52012-08-31 15:11:01 -07002176 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) {
2177 ActivityInfo ai = null;
2178 ComponentName comp = intent.getComponent();
2179 try {
2180 if (comp != null) {
2181 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId);
2182 } else {
2183 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent(
2184 intent,
2185 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
2186 flags, userId);
2187
2188 if (info != null) {
2189 ai = info.activityInfo;
2190 }
2191 }
2192 } catch (RemoteException e) {
2193 // ignore
2194 }
2195
2196 return ai;
2197 }
2198
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002199 /**
2200 * Starts the "new version setup screen" if appropriate.
2201 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002202 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002203 // Only do this once per boot.
2204 if (mCheckedForSetup) {
2205 return;
2206 }
2207
2208 // We will show this screen if the current one is a different
2209 // version than the last one shown, and we are not running in
2210 // low-level factory test mode.
2211 final ContentResolver resolver = mContext.getContentResolver();
2212 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2213 Settings.Secure.getInt(resolver,
2214 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2215 mCheckedForSetup = true;
2216
2217 // See if we should be showing the platform update setup UI.
2218 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2219 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2220 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2221
2222 // We don't allow third party apps to replace this.
2223 ResolveInfo ri = null;
2224 for (int i=0; ris != null && i<ris.size(); i++) {
2225 if ((ris.get(i).activityInfo.applicationInfo.flags
2226 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2227 ri = ris.get(i);
2228 break;
2229 }
2230 }
2231
2232 if (ri != null) {
2233 String vers = ri.activityInfo.metaData != null
2234 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2235 : null;
2236 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2237 vers = ri.activityInfo.applicationInfo.metaData.getString(
2238 Intent.METADATA_SETUP_VERSION);
2239 }
2240 String lastVers = Settings.Secure.getString(
2241 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2242 if (vers != null && !vers.equals(lastVers)) {
2243 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2244 intent.setComponent(new ComponentName(
2245 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002246 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2247 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002248 }
2249 }
2250 }
2251 }
2252
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002253 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002254 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002255 }
2256
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002257 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002258 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002259 throw new SecurityException("Isolated process not allowed to call " + caller);
2260 }
2261 }
2262
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002263 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002264 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002265 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002266 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2267 }
2268 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002269
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002270 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002271 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2272 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002273 synchronized (this) {
2274 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2275 }
2276 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002277
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002278 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002279 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002280 synchronized (this) {
2281 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2282 }
2283 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002284
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002285 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002286 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2287 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002288 synchronized (this) {
2289 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002290 }
2291 }
2292
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002293 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002294 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002295 synchronized (this) {
2296 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2297 }
2298 }
2299
2300 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002301 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2302 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002303 synchronized (this) {
2304 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2305 }
2306 }
2307
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002308 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002309 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002310 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002312
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002313 private void dispatchProcessesChanged() {
2314 int N;
2315 synchronized (this) {
2316 N = mPendingProcessChanges.size();
2317 if (mActiveProcessChanges.length < N) {
2318 mActiveProcessChanges = new ProcessChangeItem[N];
2319 }
2320 mPendingProcessChanges.toArray(mActiveProcessChanges);
2321 mAvailProcessChanges.addAll(mPendingProcessChanges);
2322 mPendingProcessChanges.clear();
2323 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2324 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002325 int i = mProcessObservers.beginBroadcast();
2326 while (i > 0) {
2327 i--;
2328 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2329 if (observer != null) {
2330 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002331 for (int j=0; j<N; j++) {
2332 ProcessChangeItem item = mActiveProcessChanges[j];
2333 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2334 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2335 + item.pid + " uid=" + item.uid + ": "
2336 + item.foregroundActivities);
2337 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2338 item.foregroundActivities);
2339 }
2340 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2341 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2342 + item.pid + " uid=" + item.uid + ": " + item.importance);
2343 observer.onImportanceChanged(item.pid, item.uid,
2344 item.importance);
2345 }
2346 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002347 } catch (RemoteException e) {
2348 }
2349 }
2350 }
2351 mProcessObservers.finishBroadcast();
2352 }
2353
2354 private void dispatchProcessDied(int pid, int uid) {
2355 int i = mProcessObservers.beginBroadcast();
2356 while (i > 0) {
2357 i--;
2358 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2359 if (observer != null) {
2360 try {
2361 observer.onProcessDied(pid, uid);
2362 } catch (RemoteException e) {
2363 }
2364 }
2365 }
2366 mProcessObservers.finishBroadcast();
2367 }
2368
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002369 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002370 final int N = mPendingActivityLaunches.size();
2371 if (N <= 0) {
2372 return;
2373 }
2374 for (int i=0; i<N; i++) {
2375 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002376 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002377 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002378 }
2379 mPendingActivityLaunches.clear();
2380 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002381
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002382 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002383 Intent intent, String resolvedType, IBinder resultTo,
2384 String resultWho, int requestCode, int startFlags,
2385 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002386 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002387 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002388 }
2389
2390 public final int startActivityAsUser(IApplicationThread caller,
2391 Intent intent, String resolvedType, IBinder resultTo,
2392 String resultWho, int requestCode, int startFlags,
2393 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002394 enforceNotIsolatedCaller("startActivity");
Dianne Hackbornd8883992012-09-07 15:58:52 -07002395 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2396 false, true, "startActivity", null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002397 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002398 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2399 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002400 }
2401
2402 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002403 Intent intent, String resolvedType, IBinder resultTo,
2404 String resultWho, int requestCode, int startFlags, String profileFile,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002405 ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002406 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07002407 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2408 false, true, "startActivityAndWait", null);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002409 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002410 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002411 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002412 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002413 return res;
2414 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002415
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002416 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002417 Intent intent, String resolvedType, IBinder resultTo,
2418 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002419 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002420 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn41203752012-08-31 14:05:51 -07002421 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2422 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002423 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002424 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002425 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002426 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002427 }
2428
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002429 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002430 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002431 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002432 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002433 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002434 // Refuse possible leaked file descriptors
2435 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2436 throw new IllegalArgumentException("File descriptors passed in Intent");
2437 }
2438
2439 IIntentSender sender = intent.getTarget();
2440 if (!(sender instanceof PendingIntentRecord)) {
2441 throw new IllegalArgumentException("Bad PendingIntent object");
2442 }
2443
2444 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002445
2446 synchronized (this) {
2447 // If this is coming from the currently resumed activity, it is
2448 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002449 if (mMainStack.mResumedActivity != null
2450 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002451 Binder.getCallingUid()) {
2452 mAppSwitchesAllowedTime = 0;
2453 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002454 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002455 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2456 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002457 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002458 }
2459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002461 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002462 // Refuse possible leaked file descriptors
2463 if (intent != null && intent.hasFileDescriptors() == true) {
2464 throw new IllegalArgumentException("File descriptors passed in Intent");
2465 }
2466
2467 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002468 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2469 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002470 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471 return false;
2472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 if (r.app == null || r.app.thread == null) {
2474 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002475 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 return false;
2477 }
2478 intent = new Intent(intent);
2479 // The caller is not allowed to change the data.
2480 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2481 // And we are resetting to find the next component...
2482 intent.setComponent(null);
2483
2484 ActivityInfo aInfo = null;
2485 try {
2486 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002487 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002489 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002490 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491
2492 // Look for the original activity in the list...
2493 final int N = resolves != null ? resolves.size() : 0;
2494 for (int i=0; i<N; i++) {
2495 ResolveInfo rInfo = resolves.get(i);
2496 if (rInfo.activityInfo.packageName.equals(r.packageName)
2497 && rInfo.activityInfo.name.equals(r.info.name)) {
2498 // We found the current one... the next matching is
2499 // after it.
2500 i++;
2501 if (i<N) {
2502 aInfo = resolves.get(i).activityInfo;
2503 }
2504 break;
2505 }
2506 }
2507 } catch (RemoteException e) {
2508 }
2509
2510 if (aInfo == null) {
2511 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002512 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 return false;
2514 }
2515
2516 intent.setComponent(new ComponentName(
2517 aInfo.applicationInfo.packageName, aInfo.name));
2518 intent.setFlags(intent.getFlags()&~(
2519 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2520 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2521 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2522 Intent.FLAG_ACTIVITY_NEW_TASK));
2523
2524 // Okay now we need to start the new activity, replacing the
2525 // currently running activity. This is a little tricky because
2526 // we want to start the new one as if the current one is finished,
2527 // but not finish the current one first so that there is no flicker.
2528 // And thus...
2529 final boolean wasFinishing = r.finishing;
2530 r.finishing = true;
2531
2532 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002533 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 final String resultWho = r.resultWho;
2535 final int requestCode = r.requestCode;
2536 r.resultTo = null;
2537 if (resultTo != null) {
2538 resultTo.removeResultsLocked(r, resultWho, requestCode);
2539 }
2540
2541 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002542 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002543 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2544 resultWho, requestCode, -1, r.launchedFromUid, 0,
2545 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 Binder.restoreCallingIdentity(origId);
2547
2548 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002549 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 return false;
2551 }
2552 return true;
2553 }
2554 }
2555
Dianne Hackborn41203752012-08-31 14:05:51 -07002556 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002558 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2559
2560 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2561 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562
Amith Yamasani742a6712011-05-04 14:49:28 -07002563 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002564 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002565 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002566 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002567 }
2568
2569 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002570 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002571 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002572 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002573 options, UserHandle.getCallingUserId());
Amith Yamasani742a6712011-05-04 14:49:28 -07002574 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002575 }
2576
Dianne Hackborn41203752012-08-31 14:05:51 -07002577 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002578 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002579 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002580
Dianne Hackborn41203752012-08-31 14:05:51 -07002581 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2582 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002583 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002584 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002585 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002586 }
2587
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002588 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002590 // Quick case: check if the top-most recent task is the same.
2591 if (N > 0 && mRecentTasks.get(0) == task) {
2592 return;
2593 }
2594 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 for (int i=0; i<N; i++) {
2596 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002597 if (task.userId == tr.userId
2598 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2599 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 mRecentTasks.remove(i);
2601 i--;
2602 N--;
2603 if (task.intent == null) {
2604 // If the new recent task we are adding is not fully
2605 // specified, then replace it with the existing recent task.
2606 task = tr;
2607 }
2608 }
2609 }
2610 if (N >= MAX_RECENT_TASKS) {
2611 mRecentTasks.remove(N-1);
2612 }
2613 mRecentTasks.add(0, task);
2614 }
2615
2616 public void setRequestedOrientation(IBinder token,
2617 int requestedOrientation) {
2618 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002619 ActivityRecord r = mMainStack.isInStackLocked(token);
2620 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 return;
2622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002624 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002625 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002626 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002627 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 if (config != null) {
2629 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002630 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002631 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 }
2633 }
2634 Binder.restoreCallingIdentity(origId);
2635 }
2636 }
2637
2638 public int getRequestedOrientation(IBinder token) {
2639 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002640 ActivityRecord r = mMainStack.isInStackLocked(token);
2641 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2643 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002644 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002645 }
2646 }
2647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 /**
2649 * This is the internal entry point for handling Activity.finish().
2650 *
2651 * @param token The Binder token referencing the Activity we want to finish.
2652 * @param resultCode Result code, if any, from this Activity.
2653 * @param resultData Result data (Intent), if any, from this Activity.
2654 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002655 * @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 -08002656 */
2657 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2658 // Refuse possible leaked file descriptors
2659 if (resultData != null && resultData.hasFileDescriptors() == true) {
2660 throw new IllegalArgumentException("File descriptors passed in Intent");
2661 }
2662
2663 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002664 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002665 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002666 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002667 if (next != null) {
2668 // ask watcher if this is allowed
2669 boolean resumeOK = true;
2670 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002671 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002673 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 }
2675
2676 if (!resumeOK) {
2677 return false;
2678 }
2679 }
2680 }
2681 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002682 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 resultData, "app-request");
2684 Binder.restoreCallingIdentity(origId);
2685 return res;
2686 }
2687 }
2688
Dianne Hackborn860755f2010-06-03 18:47:52 -07002689 public final void finishHeavyWeightApp() {
2690 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2691 != PackageManager.PERMISSION_GRANTED) {
2692 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2693 + Binder.getCallingPid()
2694 + ", uid=" + Binder.getCallingUid()
2695 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2696 Slog.w(TAG, msg);
2697 throw new SecurityException(msg);
2698 }
2699
2700 synchronized(this) {
2701 if (mHeavyWeightProcess == null) {
2702 return;
2703 }
2704
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002705 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002706 mHeavyWeightProcess.activities);
2707 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002708 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002709 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002710 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002711 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002712 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002713 null, "finish-heavy");
2714 }
2715 }
2716 }
2717
Dianne Hackborn41203752012-08-31 14:05:51 -07002718 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2719 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002720 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002721 }
2722 }
2723
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002724 public void crashApplication(int uid, int initialPid, String packageName,
2725 String message) {
2726 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2727 != PackageManager.PERMISSION_GRANTED) {
2728 String msg = "Permission Denial: crashApplication() from pid="
2729 + Binder.getCallingPid()
2730 + ", uid=" + Binder.getCallingUid()
2731 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2732 Slog.w(TAG, msg);
2733 throw new SecurityException(msg);
2734 }
2735
2736 synchronized(this) {
2737 ProcessRecord proc = null;
2738
2739 // Figure out which process to kill. We don't trust that initialPid
2740 // still has any relation to current pids, so must scan through the
2741 // list.
2742 synchronized (mPidsSelfLocked) {
2743 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2744 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002745 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002746 continue;
2747 }
2748 if (p.pid == initialPid) {
2749 proc = p;
2750 break;
2751 }
2752 for (String str : p.pkgList) {
2753 if (str.equals(packageName)) {
2754 proc = p;
2755 }
2756 }
2757 }
2758 }
2759
2760 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002761 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002762 + " initialPid=" + initialPid
2763 + " packageName=" + packageName);
2764 return;
2765 }
2766
2767 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002768 if (proc.pid == Process.myPid()) {
2769 Log.w(TAG, "crashApplication: trying to crash self!");
2770 return;
2771 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002772 long ident = Binder.clearCallingIdentity();
2773 try {
2774 proc.thread.scheduleCrash(message);
2775 } catch (RemoteException e) {
2776 }
2777 Binder.restoreCallingIdentity(ident);
2778 }
2779 }
2780 }
2781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002782 public final void finishSubActivity(IBinder token, String resultWho,
2783 int requestCode) {
2784 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002786 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 Binder.restoreCallingIdentity(origId);
2788 }
2789 }
2790
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002791 public boolean finishActivityAffinity(IBinder token) {
2792 synchronized(this) {
2793 final long origId = Binder.clearCallingIdentity();
2794 boolean res = mMainStack.finishActivityAffinityLocked(token);
2795 Binder.restoreCallingIdentity(origId);
2796 return res;
2797 }
2798 }
2799
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002800 public boolean willActivityBeVisible(IBinder token) {
2801 synchronized(this) {
2802 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002803 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2804 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002805 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002806 return true;
2807 }
2808 if (r.fullscreen && !r.finishing) {
2809 return false;
2810 }
2811 }
2812 return true;
2813 }
2814 }
2815
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002816 public void overridePendingTransition(IBinder token, String packageName,
2817 int enterAnim, int exitAnim) {
2818 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002819 ActivityRecord self = mMainStack.isInStackLocked(token);
2820 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002821 return;
2822 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002823
2824 final long origId = Binder.clearCallingIdentity();
2825
2826 if (self.state == ActivityState.RESUMED
2827 || self.state == ActivityState.PAUSING) {
2828 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002829 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002830 }
2831
2832 Binder.restoreCallingIdentity(origId);
2833 }
2834 }
2835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 * Main function for removing an existing process from the activity manager
2838 * as a result of that process going away. Clears out all connections
2839 * to the process.
2840 */
2841 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002842 boolean restarting, boolean allowRestart) {
2843 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002845 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 }
2847
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002848 if (mProfileProc == app) {
2849 clearProfilerLocked();
2850 }
2851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002853 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2854 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2855 mMainStack.mPausingActivity = null;
2856 }
2857 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2858 mMainStack.mLastPausedActivity = null;
2859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860
2861 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002862 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863
2864 boolean atTop = true;
2865 boolean hasVisibleActivities = false;
2866
2867 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002868 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002869 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 TAG, "Removing app " + app + " from history with " + i + " entries");
2871 while (i > 0) {
2872 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002873 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002874 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2876 if (r.app == app) {
2877 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002878 if (ActivityStack.DEBUG_ADD_REMOVE) {
2879 RuntimeException here = new RuntimeException("here");
2880 here.fillInStackTrace();
2881 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2882 + ": haveState=" + r.haveState
2883 + " stateNotNeeded=" + r.stateNotNeeded
2884 + " finishing=" + r.finishing
2885 + " state=" + r.state, here);
2886 }
2887 if (!r.finishing) {
2888 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002889 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2890 System.identityHashCode(r),
2891 r.task.taskId, r.shortComponentName,
2892 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002893 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002894 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895
2896 } else {
2897 // We have the current state for this activity, so
2898 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002899 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002900 TAG, "Keeping entry, setting app to null");
2901 if (r.visible) {
2902 hasVisibleActivities = true;
2903 }
2904 r.app = null;
2905 r.nowVisible = false;
2906 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002907 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2908 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 r.icicle = null;
2910 }
2911 }
2912
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002913 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 }
2915 atTop = false;
2916 }
2917
2918 app.activities.clear();
2919
2920 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002921 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 + " running instrumentation " + app.instrumentationClass);
2923 Bundle info = new Bundle();
2924 info.putString("shortMsg", "Process crashed.");
2925 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2926 }
2927
2928 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002929 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 // If there was nothing to resume, and we are not already
2931 // restarting this process, but there is a visible activity that
2932 // is hosted by the process... then make sure all visible
2933 // activities are running, taking care of restarting this
2934 // process.
2935 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002936 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 }
2938 }
2939 }
2940 }
2941
2942 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2943 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002945 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2946 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2948 return i;
2949 }
2950 }
2951 return -1;
2952 }
2953
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002954 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 IApplicationThread thread) {
2956 if (thread == null) {
2957 return null;
2958 }
2959
2960 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002961 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 }
2963
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002964 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 IApplicationThread thread) {
2966
2967 mProcDeaths[0]++;
2968
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002969 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2970 synchronized (stats) {
2971 stats.noteProcessDiedLocked(app.info.uid, pid);
2972 }
2973
Magnus Edlund7bb25812010-02-24 15:45:06 +01002974 // Clean up already done if the process has been re-started.
2975 if (app.pid == pid && app.thread != null &&
2976 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002977 if (!app.killedBackground) {
2978 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2979 + ") has died.");
2980 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002981 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002982 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 TAG, "Dying app: " + app + ", pid: " + pid
2984 + ", thread: " + thread.asBinder());
2985 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002986 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987
2988 if (doLowMem) {
2989 // If there are no longer any background processes running,
2990 // and the app that died was not running instrumentation,
2991 // then tell everyone we are now low on memory.
2992 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002993 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2994 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002995 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 haveBg = true;
2997 break;
2998 }
2999 }
3000
3001 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003002 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003003 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003004 for (int i=mLruProcesses.size()-1; i>=0; i--) {
3005 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07003006 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003007 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3008 // The low memory report is overriding any current
3009 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003010 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003011 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003012 rec.lastRequestedGc = 0;
3013 } else {
3014 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003016 rec.reportLowMemory = true;
3017 rec.lastLowMemory = now;
3018 mProcessesToGc.remove(rec);
3019 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 }
3021 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003022 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003023 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 }
3025 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003026 } else if (app.pid != pid) {
3027 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003028 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003029 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003030 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003031 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003032 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 + thread.asBinder());
3034 }
3035 }
3036
Dan Egnor42471dd2010-01-07 17:25:22 -08003037 /**
3038 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003039 * @param clearTraces causes the dump file to be erased prior to the new
3040 * traces being written, if true; when false, the new traces will be
3041 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003042 * @param firstPids of dalvik VM processes to dump stack traces for first
3043 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003044 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003045 * @return file containing stack traces, or null if no dump file is configured
3046 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003047 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003048 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003049 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3050 if (tracesPath == null || tracesPath.length() == 0) {
3051 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003053
3054 File tracesFile = new File(tracesPath);
3055 try {
3056 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003057 if (!tracesDir.exists()) {
3058 tracesFile.mkdirs();
3059 if (!SELinux.restorecon(tracesDir)) {
3060 return null;
3061 }
3062 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003063 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3064
Christopher Tate6ee412d2010-05-28 12:01:56 -07003065 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003066 tracesFile.createNewFile();
3067 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3068 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003069 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003070 return null;
3071 }
3072
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003073 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003074 return tracesFile;
3075 }
3076
3077 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003078 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003079 // Use a FileObserver to detect when traces finish writing.
3080 // The order of traces is considered important to maintain for legibility.
3081 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3082 public synchronized void onEvent(int event, String path) { notify(); }
3083 };
3084
3085 try {
3086 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003087
3088 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003089 if (firstPids != null) {
3090 try {
3091 int num = firstPids.size();
3092 for (int i = 0; i < num; i++) {
3093 synchronized (observer) {
3094 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3095 observer.wait(200); // Wait for write-close, give up after 200msec
3096 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003097 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003098 } catch (InterruptedException e) {
3099 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003100 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003101 }
3102
3103 // Next measure CPU usage.
3104 if (processStats != null) {
3105 processStats.init();
3106 System.gc();
3107 processStats.update();
3108 try {
3109 synchronized (processStats) {
3110 processStats.wait(500); // measure over 1/2 second.
3111 }
3112 } catch (InterruptedException e) {
3113 }
3114 processStats.update();
3115
3116 // We'll take the stack crawls of just the top apps using CPU.
3117 final int N = processStats.countWorkingStats();
3118 int numProcs = 0;
3119 for (int i=0; i<N && numProcs<5; i++) {
3120 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3121 if (lastPids.indexOfKey(stats.pid) >= 0) {
3122 numProcs++;
3123 try {
3124 synchronized (observer) {
3125 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3126 observer.wait(200); // Wait for write-close, give up after 200msec
3127 }
3128 } catch (InterruptedException e) {
3129 Log.wtf(TAG, e);
3130 }
3131
3132 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003133 }
3134 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003135
Dan Egnor42471dd2010-01-07 17:25:22 -08003136 } finally {
3137 observer.stopWatching();
3138 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003139
3140 if (nativeProcs != null) {
3141 int[] pids = Process.getPidsForCommands(nativeProcs);
3142 if (pids != null) {
3143 for (int pid : pids) {
3144 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3145 }
3146 }
3147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148 }
3149
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003150 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003151 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003152 return;
3153 }
3154 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3155 if (tracesPath == null || tracesPath.length() == 0) {
3156 return;
3157 }
3158
3159 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3160 StrictMode.allowThreadDiskWrites();
3161 try {
3162 final File tracesFile = new File(tracesPath);
3163 final File tracesDir = tracesFile.getParentFile();
3164 final File tracesTmp = new File(tracesDir, "__tmp__");
3165 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003166 if (!tracesDir.exists()) {
3167 tracesFile.mkdirs();
3168 if (!SELinux.restorecon(tracesDir.getPath())) {
3169 return;
3170 }
3171 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003172 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3173
3174 if (tracesFile.exists()) {
3175 tracesTmp.delete();
3176 tracesFile.renameTo(tracesTmp);
3177 }
3178 StringBuilder sb = new StringBuilder();
3179 Time tobj = new Time();
3180 tobj.set(System.currentTimeMillis());
3181 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3182 sb.append(": ");
3183 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3184 sb.append(" since ");
3185 sb.append(msg);
3186 FileOutputStream fos = new FileOutputStream(tracesFile);
3187 fos.write(sb.toString().getBytes());
3188 if (app == null) {
3189 fos.write("\n*** No application process!".getBytes());
3190 }
3191 fos.close();
3192 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3193 } catch (IOException e) {
3194 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3195 return;
3196 }
3197
3198 if (app != null) {
3199 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3200 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003201 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003202 }
3203
3204 File lastTracesFile = null;
3205 File curTracesFile = null;
3206 for (int i=9; i>=0; i--) {
3207 String name = String.format("slow%02d.txt", i);
3208 curTracesFile = new File(tracesDir, name);
3209 if (curTracesFile.exists()) {
3210 if (lastTracesFile != null) {
3211 curTracesFile.renameTo(lastTracesFile);
3212 } else {
3213 curTracesFile.delete();
3214 }
3215 }
3216 lastTracesFile = curTracesFile;
3217 }
3218 tracesFile.renameTo(curTracesFile);
3219 if (tracesTmp.exists()) {
3220 tracesTmp.renameTo(tracesFile);
3221 }
3222 } finally {
3223 StrictMode.setThreadPolicy(oldPolicy);
3224 }
3225 }
3226
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003227 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3228 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003229 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3230 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3231
Dianne Hackborn287952c2010-09-22 22:34:31 -07003232 if (mController != null) {
3233 try {
3234 // 0 == continue, -1 = kill process immediately
3235 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3236 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3237 } catch (RemoteException e) {
3238 mController = null;
3239 }
3240 }
3241
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003242 long anrTime = SystemClock.uptimeMillis();
3243 if (MONITOR_CPU_USAGE) {
3244 updateCpuStatsNow();
3245 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003246
3247 synchronized (this) {
3248 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3249 if (mShuttingDown) {
3250 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3251 return;
3252 } else if (app.notResponding) {
3253 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3254 return;
3255 } else if (app.crashing) {
3256 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3257 return;
3258 }
3259
3260 // In case we come through here for the same app before completing
3261 // this one, mark as anring now so we will bail out.
3262 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003263
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003264 // Log the ANR to the event log.
3265 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3266 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003267
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003268 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003269 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003270
3271 int parentPid = app.pid;
3272 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003273 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003274
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003275 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003276
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003277 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3278 ProcessRecord r = mLruProcesses.get(i);
3279 if (r != null && r.thread != null) {
3280 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003281 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3282 if (r.persistent) {
3283 firstPids.add(pid);
3284 } else {
3285 lastPids.put(pid, Boolean.TRUE);
3286 }
3287 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 }
3290 }
3291
Dan Egnor42471dd2010-01-07 17:25:22 -08003292 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003293 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003294 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003295 info.append("ANR in ").append(app.processName);
3296 if (activity != null && activity.shortComponentName != null) {
3297 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003298 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003299 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003301 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003302 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003303 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003304 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306
Dianne Hackborn287952c2010-09-22 22:34:31 -07003307 final ProcessStats processStats = new ProcessStats(true);
3308
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003309 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003310
Dan Egnor42471dd2010-01-07 17:25:22 -08003311 String cpuInfo = null;
3312 if (MONITOR_CPU_USAGE) {
3313 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003314 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003315 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003316 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003317 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003318 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 }
3320
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003321 info.append(processStats.printCurrentState(anrTime));
3322
Joe Onorato8a9b2202010-02-26 18:56:32 -08003323 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003324 if (tracesFile == null) {
3325 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3326 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3327 }
3328
Jeff Sharkeya353d262011-10-28 11:12:06 -07003329 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3330 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003331
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003332 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003334 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3335 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003336 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003337 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3338 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 }
3340 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003341 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003342 }
3343 }
3344
Dan Egnor42471dd2010-01-07 17:25:22 -08003345 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3346 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3347 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003348
3349 synchronized (this) {
3350 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003351 Slog.w(TAG, "Killing " + app + ": background ANR");
3352 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3353 app.processName, app.setAdj, "background ANR");
3354 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003355 return;
3356 }
3357
3358 // Set the app's notResponding state, and look up the errorReportReceiver
3359 makeAppNotRespondingLocked(app,
3360 activity != null ? activity.shortComponentName : null,
3361 annotation != null ? "ANR " + annotation : "ANR",
3362 info.toString());
3363
3364 // Bring up the infamous App Not Responding dialog
3365 Message msg = Message.obtain();
3366 HashMap map = new HashMap();
3367 msg.what = SHOW_NOT_RESPONDING_MSG;
3368 msg.obj = map;
3369 map.put("app", app);
3370 if (activity != null) {
3371 map.put("activity", activity);
3372 }
3373
3374 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 }
3377
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003378 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3379 if (!mLaunchWarningShown) {
3380 mLaunchWarningShown = true;
3381 mHandler.post(new Runnable() {
3382 @Override
3383 public void run() {
3384 synchronized (ActivityManagerService.this) {
3385 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3386 d.show();
3387 mHandler.postDelayed(new Runnable() {
3388 @Override
3389 public void run() {
3390 synchronized (ActivityManagerService.this) {
3391 d.dismiss();
3392 mLaunchWarningShown = false;
3393 }
3394 }
3395 }, 4000);
3396 }
3397 }
3398 });
3399 }
3400 }
3401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003403 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003404 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003405 int uid = Binder.getCallingUid();
3406 int pid = Binder.getCallingPid();
3407 long callingId = Binder.clearCallingIdentity();
3408 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003409 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 int pkgUid = -1;
3411 synchronized(this) {
3412 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003413 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 } catch (RemoteException e) {
3415 }
3416 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003417 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 return false;
3419 }
3420 if (uid == pkgUid || checkComponentPermission(
3421 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003422 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003423 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003424 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 } else {
3426 throw new SecurityException(pid+" does not have permission:"+
3427 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3428 "for process:"+packageName);
3429 }
3430 }
3431
3432 try {
3433 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003434 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3436 Uri.fromParts("package", packageName, null));
3437 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003438 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003439 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 } catch (RemoteException e) {
3441 }
3442 } finally {
3443 Binder.restoreCallingIdentity(callingId);
3444 }
3445 return true;
3446 }
3447
Dianne Hackborn03abb812010-01-04 18:43:19 -08003448 public void killBackgroundProcesses(final String packageName) {
3449 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3450 != PackageManager.PERMISSION_GRANTED &&
3451 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3452 != PackageManager.PERMISSION_GRANTED) {
3453 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003454 + Binder.getCallingPid()
3455 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003456 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003457 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 throw new SecurityException(msg);
3459 }
3460
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003461 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 long callingId = Binder.clearCallingIdentity();
3463 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003464 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 int pkgUid = -1;
3466 synchronized(this) {
3467 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003468 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 } catch (RemoteException e) {
3470 }
3471 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003472 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 return;
3474 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003475 killPackageProcessesLocked(packageName, pkgUid, -1,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003476 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3477 }
3478 } finally {
3479 Binder.restoreCallingIdentity(callingId);
3480 }
3481 }
3482
3483 public void killAllBackgroundProcesses() {
3484 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3485 != PackageManager.PERMISSION_GRANTED) {
3486 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3487 + Binder.getCallingPid()
3488 + ", uid=" + Binder.getCallingUid()
3489 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3490 Slog.w(TAG, msg);
3491 throw new SecurityException(msg);
3492 }
3493
3494 long callingId = Binder.clearCallingIdentity();
3495 try {
3496 synchronized(this) {
3497 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3498 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3499 final int NA = apps.size();
3500 for (int ia=0; ia<NA; ia++) {
3501 ProcessRecord app = apps.valueAt(ia);
3502 if (app.persistent) {
3503 // we don't kill persistent processes
3504 continue;
3505 }
3506 if (app.removed) {
3507 procs.add(app);
3508 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3509 app.removed = true;
3510 procs.add(app);
3511 }
3512 }
3513 }
3514
3515 int N = procs.size();
3516 for (int i=0; i<N; i++) {
3517 removeProcessLocked(procs.get(i), false, true, "kill all background");
3518 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003519 }
3520 } finally {
3521 Binder.restoreCallingIdentity(callingId);
3522 }
3523 }
3524
3525 public void forceStopPackage(final String packageName) {
3526 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3527 != PackageManager.PERMISSION_GRANTED) {
3528 String msg = "Permission Denial: forceStopPackage() from pid="
3529 + Binder.getCallingPid()
3530 + ", uid=" + Binder.getCallingUid()
3531 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003532 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003533 throw new SecurityException(msg);
3534 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003535 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003536 long callingId = Binder.clearCallingIdentity();
3537 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003538 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003539 int pkgUid = -1;
3540 synchronized(this) {
3541 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003542 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003543 } catch (RemoteException e) {
3544 }
3545 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003546 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003547 return;
3548 }
3549 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003550 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003551 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003552 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003553 } catch (IllegalArgumentException e) {
3554 Slog.w(TAG, "Failed trying to unstop package "
3555 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 }
3558 } finally {
3559 Binder.restoreCallingIdentity(callingId);
3560 }
3561 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003562
3563 /*
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003564 * The pkg name and app id have to be specified.
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003565 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003566 public void killApplicationWithAppId(String pkg, int appid) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003567 if (pkg == null) {
3568 return;
3569 }
3570 // Make sure the uid is valid.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003571 if (appid < 0) {
3572 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003573 return;
3574 }
3575 int callerUid = Binder.getCallingUid();
3576 // Only the system server can kill an application
3577 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003578 // Post an aysnc message to kill the application
3579 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003580 msg.arg1 = appid;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003581 msg.arg2 = 0;
3582 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003583 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003584 } else {
3585 throw new SecurityException(callerUid + " cannot kill pkg: " +
3586 pkg);
3587 }
3588 }
3589
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003590 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003591 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003592
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003593 final int pid = Binder.getCallingPid();
Dianne Hackborne302a162012-05-15 14:58:32 -07003594 final int uid = Binder.getCallingUid();
3595 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003596 try {
3597 synchronized (this) {
3598 // Only allow this from foreground processes, so that background
3599 // applications can't abuse it to prevent system UI from being shown.
3600 if (uid >= Process.FIRST_APPLICATION_UID) {
3601 ProcessRecord proc;
3602 synchronized (mPidsSelfLocked) {
3603 proc = mPidsSelfLocked.get(pid);
3604 }
3605 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
3606 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason
3607 + " from background process " + proc);
3608 return;
3609 }
3610 }
3611 closeSystemDialogsLocked(reason);
3612 }
3613 } finally {
3614 Binder.restoreCallingIdentity(origId);
Dianne Hackborne302a162012-05-15 14:58:32 -07003615 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003616 }
3617
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003618 void closeSystemDialogsLocked(String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003619 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003620 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003621 if (reason != null) {
3622 intent.putExtra("reason", reason);
3623 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003624 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003625
Dianne Hackborne302a162012-05-15 14:58:32 -07003626 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3627 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003628 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003629 r.stack.finishActivityLocked(r, i,
3630 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003631 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003632 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003633
Dianne Hackbornb8839dd2012-09-04 10:55:44 -07003634 broadcastIntentLocked(null, null, intent, null,
3635 null, 0, null, null, null, false, false, -1,
3636 Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003637 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003638
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003639 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003640 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003641 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003642 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3643 for (int i=pids.length-1; i>=0; i--) {
3644 infos[i] = new Debug.MemoryInfo();
3645 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003646 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003647 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003648 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003649
Dianne Hackbornb437e092011-08-05 17:50:29 -07003650 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003651 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003652 long[] pss = new long[pids.length];
3653 for (int i=pids.length-1; i>=0; i--) {
3654 pss[i] = Debug.getPss(pids[i]);
3655 }
3656 return pss;
3657 }
3658
Christopher Tate5e1ab332009-09-01 20:32:49 -07003659 public void killApplicationProcess(String processName, int uid) {
3660 if (processName == null) {
3661 return;
3662 }
3663
3664 int callerUid = Binder.getCallingUid();
3665 // Only the system server can kill an application
3666 if (callerUid == Process.SYSTEM_UID) {
3667 synchronized (this) {
3668 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003669 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003670 try {
3671 app.thread.scheduleSuicide();
3672 } catch (RemoteException e) {
3673 // If the other end already died, then our work here is done.
3674 }
3675 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003676 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003677 + processName + " / " + uid);
3678 }
3679 }
3680 } else {
3681 throw new SecurityException(callerUid + " cannot kill app process: " +
3682 processName);
3683 }
3684 }
3685
Dianne Hackborn03abb812010-01-04 18:43:19 -08003686 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003687 forceStopPackageLocked(packageName, uid, false, false, true, false,
3688 UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3690 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003691 if (!mProcessesReady) {
3692 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 intent.putExtra(Intent.EXTRA_UID, uid);
3695 broadcastIntentLocked(null, null, intent,
3696 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003697 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003698 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003700
3701 private void forceStopUserLocked(int userId) {
3702 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3703 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
3704 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3705 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3706 broadcastIntentLocked(null, null, intent,
3707 null, null, 0, null, null, null,
3708 false, false,
3709 MY_PID, Process.SYSTEM_UID, userId);
3710 }
3711
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003712 private final boolean killPackageProcessesLocked(String packageName, int appId,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003713 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3714 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003715 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716
Dianne Hackborn03abb812010-01-04 18:43:19 -08003717 // Remove all processes this package may have touched: all with the
3718 // same UID (except for the system or root user), and all whose name
3719 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003720 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003721 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3722 final int NA = apps.size();
3723 for (int ia=0; ia<NA; ia++) {
3724 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003725 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003726 // we don't kill persistent processes
3727 continue;
3728 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003729 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003730 if (doit) {
3731 procs.add(app);
3732 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003733 continue;
3734 }
3735
3736 // Skip process if it doesn't meet our oom adj requirement.
3737 if (app.setAdj < minOomAdj) {
3738 continue;
3739 }
3740
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003741 // If no package is specified, we call all processes under the
3742 // give user id.
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003743 if (packageName == null) {
3744 if (app.userId != userId) {
3745 continue;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003746 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003747 // Package has been specified, we want to hit all processes
3748 // that match it. We need to qualify this by the processes
3749 // that are running under the specified app and user ID.
3750 } else {
3751 if (UserHandle.getAppId(app.uid) != appId) {
3752 continue;
3753 }
3754 if (userId != UserHandle.USER_ALL && app.userId != userId) {
3755 continue;
3756 }
3757 if (!app.pkgList.contains(packageName)) {
3758 continue;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003759 }
3760 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003761
3762 // Process has passed all conditions, kill it!
3763 if (!doit) {
3764 return true;
3765 }
3766 app.removed = true;
3767 procs.add(app);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003768 }
3769 }
3770
3771 int N = procs.size();
3772 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003773 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003774 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003775 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003776 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003777
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003778 private final boolean forceStopPackageLocked(String name, int appId,
Christopher Tate3dacd842011-08-19 14:56:15 -07003779 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003780 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003781 int i;
3782 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003783
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003784 if (userId == UserHandle.USER_ALL && name == null) {
3785 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!");
3786 }
3787
3788 if (appId < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 try {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003790 appId = UserHandle.getAppId(
3791 AppGlobals.getPackageManager().getPackageUid(name, 0));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 } catch (RemoteException e) {
3793 }
3794 }
3795
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003796 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003797 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003798 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId
3799 + " user=" + userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003800 } else {
3801 Slog.i(TAG, "Force stopping user " + userId);
3802 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003803
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003804 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3805 while (badApps.hasNext()) {
3806 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003807 for (i=ba.size()-1; i>=0; i--) {
3808 boolean remove = false;
3809 final int entUid = ba.keyAt(i);
3810 if (name != null) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003811 if (userId == UserHandle.USER_ALL) {
3812 if (UserHandle.getAppId(entUid) == appId) {
3813 remove = true;
3814 }
3815 } else {
3816 if (entUid == UserHandle.getUid(userId, appId)) {
3817 remove = true;
3818 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003819 }
3820 } else if (UserHandle.getUserId(entUid) == userId) {
3821 remove = true;
3822 }
3823 if (remove) {
3824 ba.removeAt(i);
3825 }
3826 }
3827 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003828 badApps.remove();
3829 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003830 }
3831 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003832
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003833 boolean didSomething = killPackageProcessesLocked(name, appId, userId,
3834 -100, callerWillRestart, false, doit, evenPersistent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003835 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003837 TaskRecord lastTask = null;
3838 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003839 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003840 final boolean samePackage = r.packageName.equals(name)
3841 || (name == null && r.userId == userId);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003842 if ((userId == UserHandle.USER_ALL || r.userId == userId)
Amith Yamasani13593602012-03-22 16:16:17 -07003843 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003844 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003845 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003846 if (r.finishing) {
3847 // If this activity is just finishing, then it is not
3848 // interesting as far as something to stop.
3849 continue;
3850 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003851 return true;
3852 }
3853 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003854 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003855 if (samePackage) {
3856 if (r.app != null) {
3857 r.app.removed = true;
3858 }
3859 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003861 lastTask = r.task;
3862 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003863 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003864 i--;
3865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 }
3867 }
3868
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003869 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3870 if (!doit) {
3871 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003873 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003875
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003876 if (name == null) {
3877 // Remove all sticky broadcasts from this user.
3878 mStickyBroadcasts.remove(userId);
3879 }
3880
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003881 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003882 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent,
3883 userId, providers)) {
3884 if (!doit) {
3885 return true;
3886 }
3887 didSomething = true;
3888 }
3889 N = providers.size();
3890 for (i=0; i<N; i++) {
3891 removeDyingProviderLocked(null, providers.get(i), true);
3892 }
3893
3894 if (mIntentSenderRecords.size() > 0) {
3895 Iterator<WeakReference<PendingIntentRecord>> it
3896 = mIntentSenderRecords.values().iterator();
3897 while (it.hasNext()) {
3898 WeakReference<PendingIntentRecord> wpir = it.next();
3899 if (wpir == null) {
3900 it.remove();
3901 continue;
3902 }
3903 PendingIntentRecord pir = wpir.get();
3904 if (pir == null) {
3905 it.remove();
3906 continue;
3907 }
3908 if (name == null) {
3909 // Stopping user, remove all objects for the user.
3910 if (pir.key.userId != userId) {
3911 // Not the same user, skip it.
3912 continue;
3913 }
3914 } else {
3915 if (UserHandle.getAppId(pir.uid) != appId) {
3916 // Different app id, skip it.
3917 continue;
3918 }
3919 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) {
3920 // Different user, skip it.
3921 continue;
3922 }
3923 if (!pir.key.packageName.equals(name)) {
3924 // Different package, skip it.
3925 continue;
3926 }
3927 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003928 if (!doit) {
3929 return true;
3930 }
3931 didSomething = true;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07003932 it.remove();
3933 pir.canceled = true;
3934 if (pir.key.activity != null) {
3935 pir.key.activity.pendingResults.remove(pir.ref);
3936 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003937 }
3938 }
3939
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003940 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003941 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003942 AttributeCache ac = AttributeCache.instance();
3943 if (ac != null) {
3944 ac.removePackage(name);
3945 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003946 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003947 if (mBooted) {
3948 mMainStack.resumeTopActivityLocked(null);
3949 mMainStack.scheduleIdleLocked();
3950 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003951 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003952
3953 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 }
3955
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003956 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003957 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003959 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003960 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003961 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 + "/" + uid + ")");
3963
3964 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003965 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003966 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07003967 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
3968 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07003969 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971 boolean needRestart = false;
3972 if (app.pid > 0 && app.pid != MY_PID) {
3973 int pid = app.pid;
3974 synchronized (mPidsSelfLocked) {
3975 mPidsSelfLocked.remove(pid);
3976 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3977 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003978 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003979 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003980 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003981 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003983 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003985 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 } else {
3987 needRestart = true;
3988 }
3989 }
3990 } else {
3991 mRemovedProcesses.add(app);
3992 }
3993
3994 return needRestart;
3995 }
3996
3997 private final void processStartTimedOutLocked(ProcessRecord app) {
3998 final int pid = app.pid;
3999 boolean gone = false;
4000 synchronized (mPidsSelfLocked) {
4001 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
4002 if (knownApp != null && knownApp.thread == null) {
4003 mPidsSelfLocked.remove(pid);
4004 gone = true;
4005 }
4006 }
4007
4008 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004009 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004010 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004011 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004012 mProcessNames.remove(app.processName, app.uid);
4013 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004014 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07004015 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
4016 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004017 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07004018 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004019 // Take care of any launching providers waiting for this process.
4020 checkAppInLaunchingProvidersLocked(app, true);
4021 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004022 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004023 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
4024 app.processName, app.setAdj, "start timeout");
4025 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07004026 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004027 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07004028 try {
4029 IBackupManager bm = IBackupManager.Stub.asInterface(
4030 ServiceManager.getService(Context.BACKUP_SERVICE));
4031 bm.agentDisconnected(app.info.packageName);
4032 } catch (RemoteException e) {
4033 // Can't happen; the backup manager is local
4034 }
4035 }
Christopher Tatef46723b2012-01-26 14:19:24 -08004036 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004037 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08004038 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08004039 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004041 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004042 }
4043 }
4044
4045 private final boolean attachApplicationLocked(IApplicationThread thread,
4046 int pid) {
4047
4048 // Find the application record that is being attached... either via
4049 // the pid if we are running in multiple processes, or just pull the
4050 // next app record if we are emulating process with anonymous threads.
4051 ProcessRecord app;
4052 if (pid != MY_PID && pid >= 0) {
4053 synchronized (mPidsSelfLocked) {
4054 app = mPidsSelfLocked.get(pid);
4055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 } else {
4057 app = null;
4058 }
4059
4060 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004061 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004062 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08004063 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004065 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 } else {
4067 try {
4068 thread.scheduleExit();
4069 } catch (Exception e) {
4070 // Ignore exceptions.
4071 }
4072 }
4073 return false;
4074 }
4075
4076 // If this application record is still attached to a previous
4077 // process, clean it up now.
4078 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004079 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 }
4081
4082 // Tell the process all about itself.
4083
Joe Onorato8a9b2202010-02-26 18:56:32 -08004084 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 TAG, "Binding process pid " + pid + " to record " + app);
4086
4087 String processName = app.processName;
4088 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004089 AppDeathRecipient adr = new AppDeathRecipient(
4090 app, pid, thread);
4091 thread.asBinder().linkToDeath(adr, 0);
4092 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 } catch (RemoteException e) {
4094 app.resetPackageList();
4095 startProcessLocked(app, "link fail", processName);
4096 return false;
4097 }
4098
Doug Zongker2bec3d42009-12-04 12:52:44 -08004099 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100
4101 app.thread = thread;
4102 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004103 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4104 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 app.forcingToForeground = null;
4106 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004107 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 app.debugging = false;
4109
4110 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4111
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004112 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004113 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004115 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004116 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004117 }
4118
Joe Onorato8a9b2202010-02-26 18:56:32 -08004119 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 TAG, "New app record " + app
4121 + " thread=" + thread.asBinder() + " pid=" + pid);
4122 try {
4123 int testMode = IApplicationThread.DEBUG_OFF;
4124 if (mDebugApp != null && mDebugApp.equals(processName)) {
4125 testMode = mWaitForDebugger
4126 ? IApplicationThread.DEBUG_WAIT
4127 : IApplicationThread.DEBUG_ON;
4128 app.debugging = true;
4129 if (mDebugTransient) {
4130 mDebugApp = mOrigDebugApp;
4131 mWaitForDebugger = mOrigWaitForDebugger;
4132 }
4133 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004134 String profileFile = app.instrumentationProfileFile;
4135 ParcelFileDescriptor profileFd = null;
4136 boolean profileAutoStop = false;
4137 if (mProfileApp != null && mProfileApp.equals(processName)) {
4138 mProfileProc = app;
4139 profileFile = mProfileFile;
4140 profileFd = mProfileFd;
4141 profileAutoStop = mAutoStopProfiler;
4142 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004143 boolean enableOpenGlTrace = false;
4144 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4145 enableOpenGlTrace = true;
4146 mOpenGlTraceApp = null;
4147 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004148
Christopher Tate181fafa2009-05-14 11:12:14 -07004149 // If the app is being launched for restore or full backup, set it up specially
4150 boolean isRestrictedBackupMode = false;
4151 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4152 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004153 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004154 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4155 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004156
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004157 ensurePackageDexOpt(app.instrumentationInfo != null
4158 ? app.instrumentationInfo.packageName
4159 : app.info.packageName);
4160 if (app.instrumentationClass != null) {
4161 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004162 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004163 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004164 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004165 ApplicationInfo appInfo = app.instrumentationInfo != null
4166 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004167 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004168 if (profileFd != null) {
4169 profileFd = profileFd.dup();
4170 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004171 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004172 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004173 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4174 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004175 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004176 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004177 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004178 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004179 } catch (Exception e) {
4180 // todo: Yikes! What should we do? For now we will try to
4181 // start another process, but that could easily get us in
4182 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004183 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184
4185 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004186 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 startProcessLocked(app, "bind fail", processName);
4188 return false;
4189 }
4190
4191 // Remove this record from the list of starting applications.
4192 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004193 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4194 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004195 mProcessesOnHold.remove(app);
4196
4197 boolean badApp = false;
4198 boolean didSomething = false;
4199
4200 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004201 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004202 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004203 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 && processName.equals(hr.processName)) {
4205 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004206 if (mHeadless) {
4207 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4208 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 didSomething = true;
4210 }
4211 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004212 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213 + hr.intent.getComponent().flattenToShortString(), e);
4214 badApp = true;
4215 }
4216 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004217 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004218 }
4219 }
4220
4221 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004222 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004224 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004226 badApp = true;
4227 }
4228 }
4229
Christopher Tatef46723b2012-01-26 14:19:24 -08004230 // Check if a next-broadcast receiver is in this process...
4231 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004232 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004233 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004235 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004236 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 }
4238 }
4239
Christopher Tate181fafa2009-05-14 11:12:14 -07004240 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004241 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004242 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004243 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004244 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004245 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4246 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4247 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004248 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004249 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004250 e.printStackTrace();
4251 }
4252 }
4253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 if (badApp) {
4255 // todo: Also need to kill application to deal with all
4256 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004257 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 return false;
4259 }
4260
4261 if (!didSomething) {
4262 updateOomAdjLocked();
4263 }
4264
4265 return true;
4266 }
4267
4268 public final void attachApplication(IApplicationThread thread) {
4269 synchronized (this) {
4270 int callingPid = Binder.getCallingPid();
4271 final long origId = Binder.clearCallingIdentity();
4272 attachApplicationLocked(thread, callingPid);
4273 Binder.restoreCallingIdentity(origId);
4274 }
4275 }
4276
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004277 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004279 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4280 if (stopProfiling) {
4281 synchronized (this) {
4282 if (mProfileProc == r.app) {
4283 if (mProfileFd != null) {
4284 try {
4285 mProfileFd.close();
4286 } catch (IOException e) {
4287 }
4288 clearProfilerLocked();
4289 }
4290 }
4291 }
4292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004293 Binder.restoreCallingIdentity(origId);
4294 }
4295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004297 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004298 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004300
4301 synchronized (this) {
4302 updateEventDispatchingLocked();
4303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004304 }
4305
Dianne Hackborn661cd522011-08-22 00:26:20 -07004306 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004307 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004308 mWindowManager.showBootMessage(msg, always);
4309 }
4310
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004311 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004312 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004313 final long token = Binder.clearCallingIdentity();
4314 try {
4315 synchronized (this) {
4316 if (mLockScreenShown) {
4317 mLockScreenShown = false;
4318 comeOutOfSleepIfNeededLocked();
4319 }
4320 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004321 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004322 } finally {
4323 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004324 }
4325 }
4326
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004327 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004328 IntentFilter pkgFilter = new IntentFilter();
4329 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4330 pkgFilter.addDataScheme("package");
4331 mContext.registerReceiver(new BroadcastReceiver() {
4332 @Override
4333 public void onReceive(Context context, Intent intent) {
4334 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4335 if (pkgs != null) {
4336 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004337 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004338 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4339 setResultCode(Activity.RESULT_OK);
4340 return;
4341 }
4342 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004343 }
4344 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004345 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004346 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004347
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004348 synchronized (this) {
4349 // Ensure that any processes we had put on hold are now started
4350 // up.
4351 final int NP = mProcessesOnHold.size();
4352 if (NP > 0) {
4353 ArrayList<ProcessRecord> procs =
4354 new ArrayList<ProcessRecord>(mProcessesOnHold);
4355 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004356 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4357 + procs.get(ip));
4358 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004359 }
4360 }
4361
4362 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004363 // Start looking for apps that are abusing wake locks.
4364 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004365 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004366 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004367 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004368 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004369 for (int i=0; i<mStartedUsers.size(); i++) {
4370 UserStartedState uss = mStartedUsers.valueAt(i);
4371 if (uss.mState == UserStartedState.STATE_BOOTING) {
4372 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004373 final int userId = mStartedUsers.keyAt(i);
4374 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4375 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4376 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004377 null, null, 0, null, null,
4378 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004379 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004380 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004381 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004382 }
4383 }
4384 }
4385
4386 final void ensureBootCompleted() {
4387 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004388 boolean enableScreen;
4389 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004390 booting = mBooting;
4391 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004392 enableScreen = !mBooted;
4393 mBooted = true;
4394 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004395
4396 if (booting) {
4397 finishBooting();
4398 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004399
4400 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004401 enableScreenAfterBoot();
4402 }
4403 }
4404
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004405 public final void activityPaused(IBinder token) {
4406 final long origId = Binder.clearCallingIdentity();
4407 mMainStack.activityPaused(token, false);
4408 Binder.restoreCallingIdentity(origId);
4409 }
4410
4411 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4412 CharSequence description) {
4413 if (localLOGV) Slog.v(
4414 TAG, "Activity stopped: token=" + token);
4415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004416 // Refuse possible leaked file descriptors
4417 if (icicle != null && icicle.hasFileDescriptors()) {
4418 throw new IllegalArgumentException("File descriptors passed in Bundle");
4419 }
4420
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004421 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422
4423 final long origId = Binder.clearCallingIdentity();
4424
4425 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004426 r = mMainStack.isInStackLocked(token);
4427 if (r != null) {
4428 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004429 }
4430 }
4431
4432 if (r != null) {
4433 sendPendingThumbnail(r, null, null, null, false);
4434 }
4435
4436 trimApplications();
4437
4438 Binder.restoreCallingIdentity(origId);
4439 }
4440
4441 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004442 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004443 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004444 }
4445
4446 public String getCallingPackage(IBinder token) {
4447 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004448 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004449 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004450 }
4451 }
4452
4453 public ComponentName getCallingActivity(IBinder token) {
4454 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004455 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004456 return r != null ? r.intent.getComponent() : null;
4457 }
4458 }
4459
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004460 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004461 ActivityRecord r = mMainStack.isInStackLocked(token);
4462 if (r == null) {
4463 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004464 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004465 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004466 }
4467
4468 public ComponentName getActivityClassForToken(IBinder token) {
4469 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004470 ActivityRecord r = mMainStack.isInStackLocked(token);
4471 if (r == null) {
4472 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004473 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004474 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475 }
4476 }
4477
4478 public String getPackageForToken(IBinder token) {
4479 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004480 ActivityRecord r = mMainStack.isInStackLocked(token);
4481 if (r == null) {
4482 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004483 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004484 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 }
4486 }
4487
4488 public IIntentSender getIntentSender(int type,
4489 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004490 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004491 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004492 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004494 if (intents != null) {
4495 if (intents.length < 1) {
4496 throw new IllegalArgumentException("Intents array length must be >= 1");
4497 }
4498 for (int i=0; i<intents.length; i++) {
4499 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004500 if (intent != null) {
4501 if (intent.hasFileDescriptors()) {
4502 throw new IllegalArgumentException("File descriptors passed in Intent");
4503 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004504 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004505 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4506 throw new IllegalArgumentException(
4507 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4508 }
4509 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004510 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004511 }
4512 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004513 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004514 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004515 }
4516 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004517 if (options != null) {
4518 if (options.hasFileDescriptors()) {
4519 throw new IllegalArgumentException("File descriptors passed in options");
4520 }
4521 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004523 synchronized(this) {
4524 int callingUid = Binder.getCallingUid();
Dianne Hackborn41203752012-08-31 14:05:51 -07004525 userId = handleIncomingUserLocked(Binder.getCallingPid(), callingUid, userId,
4526 false, true, "getIntentSender", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004527 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004528 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004529 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004530 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4531 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 String msg = "Permission Denial: getIntentSender() from pid="
4533 + Binder.getCallingPid()
4534 + ", uid=" + Binder.getCallingUid()
4535 + ", (need uid=" + uid + ")"
4536 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004537 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004538 throw new SecurityException(msg);
4539 }
4540 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004541
4542 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004543 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 } catch (RemoteException e) {
4546 throw new SecurityException(e);
4547 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004548 }
4549 }
4550
Dianne Hackborn41203752012-08-31 14:05:51 -07004551 IIntentSender getIntentSenderLocked(int type, String packageName,
4552 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004553 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4554 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004555 if (DEBUG_MU)
4556 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004557 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004558 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004559 activity = mMainStack.isInStackLocked(token);
4560 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004561 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004562 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004563 if (activity.finishing) {
4564 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004565 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004566 }
4567
4568 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4569 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4570 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4571 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4572 |PendingIntent.FLAG_UPDATE_CURRENT);
4573
4574 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4575 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004576 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004577 WeakReference<PendingIntentRecord> ref;
4578 ref = mIntentSenderRecords.get(key);
4579 PendingIntentRecord rec = ref != null ? ref.get() : null;
4580 if (rec != null) {
4581 if (!cancelCurrent) {
4582 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004583 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004584 rec.key.requestIntent.replaceExtras(intents != null ?
4585 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004586 }
4587 if (intents != null) {
4588 intents[intents.length-1] = rec.key.requestIntent;
4589 rec.key.allIntents = intents;
4590 rec.key.allResolvedTypes = resolvedTypes;
4591 } else {
4592 rec.key.allIntents = null;
4593 rec.key.allResolvedTypes = null;
4594 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 return rec;
4597 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004598 rec.canceled = true;
4599 mIntentSenderRecords.remove(key);
4600 }
4601 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004602 return rec;
4603 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004604 rec = new PendingIntentRecord(this, key, callingUid);
4605 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004606 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004607 if (activity.pendingResults == null) {
4608 activity.pendingResults
4609 = new HashSet<WeakReference<PendingIntentRecord>>();
4610 }
4611 activity.pendingResults.add(rec.ref);
4612 }
4613 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004614 }
4615
4616 public void cancelIntentSender(IIntentSender sender) {
4617 if (!(sender instanceof PendingIntentRecord)) {
4618 return;
4619 }
4620 synchronized(this) {
4621 PendingIntentRecord rec = (PendingIntentRecord)sender;
4622 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004623 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004624 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4625 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004626 String msg = "Permission Denial: cancelIntentSender() from pid="
4627 + Binder.getCallingPid()
4628 + ", uid=" + Binder.getCallingUid()
4629 + " is not allowed to cancel packges "
4630 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004631 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004632 throw new SecurityException(msg);
4633 }
4634 } catch (RemoteException e) {
4635 throw new SecurityException(e);
4636 }
4637 cancelIntentSenderLocked(rec, true);
4638 }
4639 }
4640
4641 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4642 rec.canceled = true;
4643 mIntentSenderRecords.remove(rec.key);
4644 if (cleanActivity && rec.key.activity != null) {
4645 rec.key.activity.pendingResults.remove(rec.ref);
4646 }
4647 }
4648
4649 public String getPackageForIntentSender(IIntentSender pendingResult) {
4650 if (!(pendingResult instanceof PendingIntentRecord)) {
4651 return null;
4652 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004653 try {
4654 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4655 return res.key.packageName;
4656 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004657 }
4658 return null;
4659 }
4660
Christopher Tatec4a07d12012-04-06 14:19:13 -07004661 public int getUidForIntentSender(IIntentSender sender) {
4662 if (sender instanceof PendingIntentRecord) {
4663 try {
4664 PendingIntentRecord res = (PendingIntentRecord)sender;
4665 return res.uid;
4666 } catch (ClassCastException e) {
4667 }
4668 }
4669 return -1;
4670 }
4671
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004672 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4673 if (!(pendingResult instanceof PendingIntentRecord)) {
4674 return false;
4675 }
4676 try {
4677 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4678 if (res.key.allIntents == null) {
4679 return false;
4680 }
4681 for (int i=0; i<res.key.allIntents.length; i++) {
4682 Intent intent = res.key.allIntents[i];
4683 if (intent.getPackage() != null && intent.getComponent() != null) {
4684 return false;
4685 }
4686 }
4687 return true;
4688 } catch (ClassCastException e) {
4689 }
4690 return false;
4691 }
4692
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004693 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4694 if (!(pendingResult instanceof PendingIntentRecord)) {
4695 return false;
4696 }
4697 try {
4698 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4699 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4700 return true;
4701 }
4702 return false;
4703 } catch (ClassCastException e) {
4704 }
4705 return false;
4706 }
4707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004708 public void setProcessLimit(int max) {
4709 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4710 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004711 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004712 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004713 mProcessLimitOverride = max;
4714 }
4715 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004716 }
4717
4718 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004719 synchronized (this) {
4720 return mProcessLimitOverride;
4721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004722 }
4723
4724 void foregroundTokenDied(ForegroundToken token) {
4725 synchronized (ActivityManagerService.this) {
4726 synchronized (mPidsSelfLocked) {
4727 ForegroundToken cur
4728 = mForegroundProcesses.get(token.pid);
4729 if (cur != token) {
4730 return;
4731 }
4732 mForegroundProcesses.remove(token.pid);
4733 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4734 if (pr == null) {
4735 return;
4736 }
4737 pr.forcingToForeground = null;
4738 pr.foregroundServices = false;
4739 }
4740 updateOomAdjLocked();
4741 }
4742 }
4743
4744 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4745 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4746 "setProcessForeground()");
4747 synchronized(this) {
4748 boolean changed = false;
4749
4750 synchronized (mPidsSelfLocked) {
4751 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004752 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004753 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004754 return;
4755 }
4756 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4757 if (oldToken != null) {
4758 oldToken.token.unlinkToDeath(oldToken, 0);
4759 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004760 if (pr != null) {
4761 pr.forcingToForeground = null;
4762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004763 changed = true;
4764 }
4765 if (isForeground && token != null) {
4766 ForegroundToken newToken = new ForegroundToken() {
4767 public void binderDied() {
4768 foregroundTokenDied(this);
4769 }
4770 };
4771 newToken.pid = pid;
4772 newToken.token = token;
4773 try {
4774 token.linkToDeath(newToken, 0);
4775 mForegroundProcesses.put(pid, newToken);
4776 pr.forcingToForeground = token;
4777 changed = true;
4778 } catch (RemoteException e) {
4779 // If the process died while doing this, we will later
4780 // do the cleanup with the process death link.
4781 }
4782 }
4783 }
4784
4785 if (changed) {
4786 updateOomAdjLocked();
4787 }
4788 }
4789 }
4790
4791 // =========================================================
4792 // PERMISSIONS
4793 // =========================================================
4794
4795 static class PermissionController extends IPermissionController.Stub {
4796 ActivityManagerService mActivityManagerService;
4797 PermissionController(ActivityManagerService activityManagerService) {
4798 mActivityManagerService = activityManagerService;
4799 }
4800
4801 public boolean checkPermission(String permission, int pid, int uid) {
4802 return mActivityManagerService.checkPermission(permission, pid,
4803 uid) == PackageManager.PERMISSION_GRANTED;
4804 }
4805 }
4806
4807 /**
4808 * This can be called with or without the global lock held.
4809 */
4810 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004811 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004812 // We might be performing an operation on behalf of an indirect binder
4813 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4814 // client identity accordingly before proceeding.
4815 Identity tlsIdentity = sCallerIdentity.get();
4816 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004817 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004818 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4819 uid = tlsIdentity.uid;
4820 pid = tlsIdentity.pid;
4821 }
4822
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004823 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004824 return PackageManager.PERMISSION_GRANTED;
4825 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004826
4827 return ActivityManager.checkComponentPermission(permission, uid,
4828 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004829 }
4830
4831 /**
4832 * As the only public entry point for permissions checking, this method
4833 * can enforce the semantic that requesting a check on a null global
4834 * permission is automatically denied. (Internally a null permission
4835 * string is used when calling {@link #checkComponentPermission} in cases
4836 * when only uid-based security is needed.)
4837 *
4838 * This can be called with or without the global lock held.
4839 */
4840 public int checkPermission(String permission, int pid, int uid) {
4841 if (permission == null) {
4842 return PackageManager.PERMISSION_DENIED;
4843 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004844 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004845 }
4846
4847 /**
4848 * Binder IPC calls go through the public entry point.
4849 * This can be called with or without the global lock held.
4850 */
4851 int checkCallingPermission(String permission) {
4852 return checkPermission(permission,
4853 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004854 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004855 }
4856
4857 /**
4858 * This can be called with or without the global lock held.
4859 */
4860 void enforceCallingPermission(String permission, String func) {
4861 if (checkCallingPermission(permission)
4862 == PackageManager.PERMISSION_GRANTED) {
4863 return;
4864 }
4865
4866 String msg = "Permission Denial: " + func + " from pid="
4867 + Binder.getCallingPid()
4868 + ", uid=" + Binder.getCallingUid()
4869 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004870 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004871 throw new SecurityException(msg);
4872 }
4873
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004874 /**
4875 * Determine if UID is holding permissions required to access {@link Uri} in
4876 * the given {@link ProviderInfo}. Final permission checking is always done
4877 * in {@link ContentProvider}.
4878 */
4879 private final boolean checkHoldingPermissionsLocked(
4880 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004881 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4882 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004883
4884 if (pi.applicationInfo.uid == uid) {
4885 return true;
4886 } else if (!pi.exported) {
4887 return false;
4888 }
4889
4890 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4891 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004892 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004893 // check if target holds top-level <provider> permissions
4894 if (!readMet && pi.readPermission != null
4895 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4896 readMet = true;
4897 }
4898 if (!writeMet && pi.writePermission != null
4899 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4900 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004901 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004902
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004903 // track if unprotected read/write is allowed; any denied
4904 // <path-permission> below removes this ability
4905 boolean allowDefaultRead = pi.readPermission == null;
4906 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004907
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004908 // check if target holds any <path-permission> that match uri
4909 final PathPermission[] pps = pi.pathPermissions;
4910 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004911 final String path = uri.getPath();
4912 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004913 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004914 i--;
4915 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004916 if (pp.match(path)) {
4917 if (!readMet) {
4918 final String pprperm = pp.getReadPermission();
4919 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4920 + pprperm + " for " + pp.getPath()
4921 + ": match=" + pp.match(path)
4922 + " check=" + pm.checkUidPermission(pprperm, uid));
4923 if (pprperm != null) {
4924 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4925 readMet = true;
4926 } else {
4927 allowDefaultRead = false;
4928 }
4929 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004930 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004931 if (!writeMet) {
4932 final String ppwperm = pp.getWritePermission();
4933 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4934 + ppwperm + " for " + pp.getPath()
4935 + ": match=" + pp.match(path)
4936 + " check=" + pm.checkUidPermission(ppwperm, uid));
4937 if (ppwperm != null) {
4938 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4939 writeMet = true;
4940 } else {
4941 allowDefaultWrite = false;
4942 }
4943 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004944 }
4945 }
4946 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004947 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004948
4949 // grant unprotected <provider> read/write, if not blocked by
4950 // <path-permission> above
4951 if (allowDefaultRead) readMet = true;
4952 if (allowDefaultWrite) writeMet = true;
4953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004954 } catch (RemoteException e) {
4955 return false;
4956 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004957
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004958 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004959 }
4960
4961 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4962 int modeFlags) {
4963 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004964 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004965 return true;
4966 }
4967 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4968 if (perms == null) return false;
4969 UriPermission perm = perms.get(uri);
4970 if (perm == null) return false;
4971 return (modeFlags&perm.modeFlags) == modeFlags;
4972 }
4973
4974 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004975 enforceNotIsolatedCaller("checkUriPermission");
4976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004977 // Another redirected-binder-call permissions check as in
4978 // {@link checkComponentPermission}.
4979 Identity tlsIdentity = sCallerIdentity.get();
4980 if (tlsIdentity != null) {
4981 uid = tlsIdentity.uid;
4982 pid = tlsIdentity.pid;
4983 }
4984
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004985 uid = UserHandle.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004986 // Our own process gets to do everything.
4987 if (pid == MY_PID) {
4988 return PackageManager.PERMISSION_GRANTED;
4989 }
4990 synchronized(this) {
4991 return checkUriPermissionLocked(uri, uid, modeFlags)
4992 ? PackageManager.PERMISSION_GRANTED
4993 : PackageManager.PERMISSION_DENIED;
4994 }
4995 }
4996
Dianne Hackborn39792d22010-08-19 18:01:52 -07004997 /**
4998 * Check if the targetPkg can be granted permission to access uri by
4999 * the callingUid using the given modeFlags. Throws a security exception
5000 * if callingUid is not allowed to do this. Returns the uid of the target
5001 * if the URI permission grant should be performed; returns -1 if it is not
5002 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005003 * If you already know the uid of the target, you can supply it in
5004 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07005005 */
5006 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005007 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005008 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5009 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5010 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005011 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005012 }
5013
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005014 if (targetPkg != null) {
5015 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5016 "Checking grant " + targetPkg + " permission to " + uri);
5017 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005018
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005019 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005020
5021 // If this is not a content: uri, we can't do anything with it.
5022 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005023 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005024 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005025 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005026 }
5027
5028 String name = uri.getAuthority();
5029 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07005030 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005031 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005032 if (cpr != null) {
5033 pi = cpr.info;
5034 } else {
5035 try {
5036 pi = pm.resolveContentProvider(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005037 PackageManager.GET_URI_PERMISSION_PATTERNS, UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 } catch (RemoteException ex) {
5039 }
5040 }
5041 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005042 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07005043 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005044 }
5045
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005046 int targetUid = lastTargetUid;
5047 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005048 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005049 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005050 if (targetUid < 0) {
5051 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5052 "Can't grant URI permission no uid for: " + targetPkg);
5053 return -1;
5054 }
5055 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07005056 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005058 }
5059
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005060 if (targetUid >= 0) {
5061 // First... does the target actually need this permission?
5062 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
5063 // No need to grant the target this permission.
5064 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
5065 "Target " + targetPkg + " already has full permission to " + uri);
5066 return -1;
5067 }
5068 } else {
5069 // First... there is no target package, so can anyone access it?
5070 boolean allowed = pi.exported;
5071 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5072 if (pi.readPermission != null) {
5073 allowed = false;
5074 }
5075 }
5076 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5077 if (pi.writePermission != null) {
5078 allowed = false;
5079 }
5080 }
5081 if (allowed) {
5082 return -1;
5083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005084 }
5085
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005086 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005087 if (!pi.grantUriPermissions) {
5088 throw new SecurityException("Provider " + pi.packageName
5089 + "/" + pi.name
5090 + " does not allow granting of Uri permissions (uri "
5091 + uri + ")");
5092 }
5093 if (pi.uriPermissionPatterns != null) {
5094 final int N = pi.uriPermissionPatterns.length;
5095 boolean allowed = false;
5096 for (int i=0; i<N; i++) {
5097 if (pi.uriPermissionPatterns[i] != null
5098 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5099 allowed = true;
5100 break;
5101 }
5102 }
5103 if (!allowed) {
5104 throw new SecurityException("Provider " + pi.packageName
5105 + "/" + pi.name
5106 + " does not allow granting of permission to path of Uri "
5107 + uri);
5108 }
5109 }
5110
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005111 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005112 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005113 if (callingUid != Process.myUid()) {
5114 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5115 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5116 throw new SecurityException("Uid " + callingUid
5117 + " does not have permission to uri " + uri);
5118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005119 }
5120 }
5121
Dianne Hackborn39792d22010-08-19 18:01:52 -07005122 return targetUid;
5123 }
5124
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005125 public int checkGrantUriPermission(int callingUid, String targetPkg,
5126 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005127 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005128 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005129 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005130 }
5131 }
5132
Dianne Hackborn39792d22010-08-19 18:01:52 -07005133 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5134 Uri uri, int modeFlags, UriPermissionOwner owner) {
5135 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5136 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5137 if (modeFlags == 0) {
5138 return;
5139 }
5140
5141 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005142 // to the uri, and the target doesn't. Let's now give this to
5143 // the target.
5144
Joe Onorato8a9b2202010-02-26 18:56:32 -08005145 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005146 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005147
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005148 HashMap<Uri, UriPermission> targetUris
5149 = mGrantedUriPermissions.get(targetUid);
5150 if (targetUris == null) {
5151 targetUris = new HashMap<Uri, UriPermission>();
5152 mGrantedUriPermissions.put(targetUid, targetUris);
5153 }
5154
5155 UriPermission perm = targetUris.get(uri);
5156 if (perm == null) {
5157 perm = new UriPermission(targetUid, uri);
5158 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005159 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005161 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005162 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005163 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005164 } else {
5165 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5166 perm.readOwners.add(owner);
5167 owner.addReadPermission(perm);
5168 }
5169 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5170 perm.writeOwners.add(owner);
5171 owner.addWritePermission(perm);
5172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005173 }
5174 }
5175
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005176 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5177 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005178 if (targetPkg == null) {
5179 throw new NullPointerException("targetPkg");
5180 }
5181
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005182 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005183 if (targetUid < 0) {
5184 return;
5185 }
5186
5187 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5188 }
5189
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005190 static class NeededUriGrants extends ArrayList<Uri> {
5191 final String targetPkg;
5192 final int targetUid;
5193 final int flags;
5194
5195 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5196 targetPkg = _targetPkg;
5197 targetUid = _targetUid;
5198 flags = _flags;
5199 }
5200 }
5201
Dianne Hackborn39792d22010-08-19 18:01:52 -07005202 /**
5203 * Like checkGrantUriPermissionLocked, but takes an Intent.
5204 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005205 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5206 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005207 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005208 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5209 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005210 + " from " + intent + "; flags=0x"
5211 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5212
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005213 if (targetPkg == null) {
5214 throw new NullPointerException("targetPkg");
5215 }
5216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005218 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 }
5220 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005221 ClipData clip = intent.getClipData();
5222 if (data == null && clip == null) {
5223 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005224 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005225 if (data != null) {
5226 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5227 mode, needed != null ? needed.targetUid : -1);
5228 if (target > 0) {
5229 if (needed == null) {
5230 needed = new NeededUriGrants(targetPkg, target, mode);
5231 }
5232 needed.add(data);
5233 }
5234 }
5235 if (clip != null) {
5236 for (int i=0; i<clip.getItemCount(); i++) {
5237 Uri uri = clip.getItemAt(i).getUri();
5238 if (uri != null) {
5239 int target = -1;
5240 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5241 mode, needed != null ? needed.targetUid : -1);
5242 if (target > 0) {
5243 if (needed == null) {
5244 needed = new NeededUriGrants(targetPkg, target, mode);
5245 }
5246 needed.add(uri);
5247 }
5248 } else {
5249 Intent clipIntent = clip.getItemAt(i).getIntent();
5250 if (clipIntent != null) {
5251 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5252 callingUid, targetPkg, clipIntent, mode, needed);
5253 if (newNeeded != null) {
5254 needed = newNeeded;
5255 }
5256 }
5257 }
5258 }
5259 }
5260
5261 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005262 }
5263
5264 /**
5265 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5266 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005267 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5268 UriPermissionOwner owner) {
5269 if (needed != null) {
5270 for (int i=0; i<needed.size(); i++) {
5271 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5272 needed.get(i), needed.flags, owner);
5273 }
5274 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005275 }
5276
5277 void grantUriPermissionFromIntentLocked(int callingUid,
5278 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005279 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005280 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005281 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005282 return;
5283 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005284
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005285 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005286 }
5287
5288 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5289 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005290 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005291 synchronized(this) {
5292 final ProcessRecord r = getRecordForAppLocked(caller);
5293 if (r == null) {
5294 throw new SecurityException("Unable to find app for caller "
5295 + caller
5296 + " when granting permission to uri " + uri);
5297 }
5298 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005299 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005300 }
5301 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005302 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 }
5304
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005305 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005306 null);
5307 }
5308 }
5309
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005310 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005311 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5312 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5313 HashMap<Uri, UriPermission> perms
5314 = mGrantedUriPermissions.get(perm.uid);
5315 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005316 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005317 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005318 perms.remove(perm.uri);
5319 if (perms.size() == 0) {
5320 mGrantedUriPermissions.remove(perm.uid);
5321 }
5322 }
5323 }
5324 }
5325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005326 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5327 int modeFlags) {
5328 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5329 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5330 if (modeFlags == 0) {
5331 return;
5332 }
5333
Joe Onorato8a9b2202010-02-26 18:56:32 -08005334 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005335 "Revoking all granted permissions to " + uri);
5336
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005337 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005338
5339 final String authority = uri.getAuthority();
5340 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005341 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005342 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005343 if (cpr != null) {
5344 pi = cpr.info;
5345 } else {
5346 try {
5347 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005348 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005349 } catch (RemoteException ex) {
5350 }
5351 }
5352 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005353 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005354 return;
5355 }
5356
5357 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005358 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005359 // Right now, if you are not the original owner of the permission,
5360 // you are not allowed to revoke it.
5361 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5362 throw new SecurityException("Uid " + callingUid
5363 + " does not have permission to uri " + uri);
5364 //}
5365 }
5366
5367 // Go through all of the permissions and remove any that match.
5368 final List<String> SEGMENTS = uri.getPathSegments();
5369 if (SEGMENTS != null) {
5370 final int NS = SEGMENTS.size();
5371 int N = mGrantedUriPermissions.size();
5372 for (int i=0; i<N; i++) {
5373 HashMap<Uri, UriPermission> perms
5374 = mGrantedUriPermissions.valueAt(i);
5375 Iterator<UriPermission> it = perms.values().iterator();
5376 toploop:
5377 while (it.hasNext()) {
5378 UriPermission perm = it.next();
5379 Uri targetUri = perm.uri;
5380 if (!authority.equals(targetUri.getAuthority())) {
5381 continue;
5382 }
5383 List<String> targetSegments = targetUri.getPathSegments();
5384 if (targetSegments == null) {
5385 continue;
5386 }
5387 if (targetSegments.size() < NS) {
5388 continue;
5389 }
5390 for (int j=0; j<NS; j++) {
5391 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5392 continue toploop;
5393 }
5394 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005395 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005396 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005397 perm.clearModes(modeFlags);
5398 if (perm.modeFlags == 0) {
5399 it.remove();
5400 }
5401 }
5402 if (perms.size() == 0) {
5403 mGrantedUriPermissions.remove(
5404 mGrantedUriPermissions.keyAt(i));
5405 N--;
5406 i--;
5407 }
5408 }
5409 }
5410 }
5411
5412 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5413 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005414 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005415 synchronized(this) {
5416 final ProcessRecord r = getRecordForAppLocked(caller);
5417 if (r == null) {
5418 throw new SecurityException("Unable to find app for caller "
5419 + caller
5420 + " when revoking permission to uri " + uri);
5421 }
5422 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005423 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005424 return;
5425 }
5426
5427 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5428 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5429 if (modeFlags == 0) {
5430 return;
5431 }
5432
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005433 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005434
5435 final String authority = uri.getAuthority();
5436 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005437 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438 if (cpr != null) {
5439 pi = cpr.info;
5440 } else {
5441 try {
5442 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005443 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005444 } catch (RemoteException ex) {
5445 }
5446 }
5447 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005448 Slog.w(TAG, "No content provider found for permission revoke: "
5449 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 return;
5451 }
5452
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005453 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 }
5455 }
5456
Dianne Hackborn7e269642010-08-25 19:50:20 -07005457 @Override
5458 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005459 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005460 synchronized(this) {
5461 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5462 return owner.getExternalTokenLocked();
5463 }
5464 }
5465
5466 @Override
5467 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5468 Uri uri, int modeFlags) {
5469 synchronized(this) {
5470 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5471 if (owner == null) {
5472 throw new IllegalArgumentException("Unknown owner: " + token);
5473 }
5474 if (fromUid != Binder.getCallingUid()) {
5475 if (Binder.getCallingUid() != Process.myUid()) {
5476 // Only system code can grant URI permissions on behalf
5477 // of other users.
5478 throw new SecurityException("nice try");
5479 }
5480 }
5481 if (targetPkg == null) {
5482 throw new IllegalArgumentException("null target");
5483 }
5484 if (uri == null) {
5485 throw new IllegalArgumentException("null uri");
5486 }
5487
5488 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5489 }
5490 }
5491
5492 @Override
5493 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5494 synchronized(this) {
5495 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5496 if (owner == null) {
5497 throw new IllegalArgumentException("Unknown owner: " + token);
5498 }
5499
5500 if (uri == null) {
5501 owner.removeUriPermissionsLocked(mode);
5502 } else {
5503 owner.removeUriPermissionLocked(uri, mode);
5504 }
5505 }
5506 }
5507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005508 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5509 synchronized (this) {
5510 ProcessRecord app =
5511 who != null ? getRecordForAppLocked(who) : null;
5512 if (app == null) return;
5513
5514 Message msg = Message.obtain();
5515 msg.what = WAIT_FOR_DEBUGGER_MSG;
5516 msg.obj = app;
5517 msg.arg1 = waiting ? 1 : 0;
5518 mHandler.sendMessage(msg);
5519 }
5520 }
5521
5522 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005523 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5524 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005526 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005527 outInfo.threshold = homeAppMem;
5528 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5529 outInfo.hiddenAppThreshold = hiddenAppMem;
5530 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005531 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005532 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5533 ProcessList.VISIBLE_APP_ADJ);
5534 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5535 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536 }
5537
5538 // =========================================================
5539 // TASK MANAGEMENT
5540 // =========================================================
5541
5542 public List getTasks(int maxNum, int flags,
5543 IThumbnailReceiver receiver) {
5544 ArrayList list = new ArrayList();
5545
5546 PendingThumbnailsRecord pending = null;
5547 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005548 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549
5550 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005551 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005552 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5553 + ", receiver=" + receiver);
5554
5555 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5556 != PackageManager.PERMISSION_GRANTED) {
5557 if (receiver != null) {
5558 // If the caller wants to wait for pending thumbnails,
5559 // it ain't gonna get them.
5560 try {
5561 receiver.finished();
5562 } catch (RemoteException ex) {
5563 }
5564 }
5565 String msg = "Permission Denial: getTasks() from pid="
5566 + Binder.getCallingPid()
5567 + ", uid=" + Binder.getCallingUid()
5568 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005569 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 throw new SecurityException(msg);
5571 }
5572
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005573 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005574 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005575 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005576 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 TaskRecord curTask = null;
5578 int numActivities = 0;
5579 int numRunning = 0;
5580 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005581 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005583 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005584
5585 // Initialize state for next task if needed.
5586 if (top == null ||
5587 (top.state == ActivityState.INITIALIZING
5588 && top.task == r.task)) {
5589 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 curTask = r.task;
5591 numActivities = numRunning = 0;
5592 }
5593
5594 // Add 'r' into the current task.
5595 numActivities++;
5596 if (r.app != null && r.app.thread != null) {
5597 numRunning++;
5598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599
Joe Onorato8a9b2202010-02-26 18:56:32 -08005600 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 TAG, r.intent.getComponent().flattenToShortString()
5602 + ": task=" + r.task);
5603
5604 // If the next one is a different task, generate a new
5605 // TaskInfo entry for what we have.
5606 if (next == null || next.task != curTask) {
5607 ActivityManager.RunningTaskInfo ci
5608 = new ActivityManager.RunningTaskInfo();
5609 ci.id = curTask.taskId;
5610 ci.baseActivity = r.intent.getComponent();
5611 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005612 if (top.thumbHolder != null) {
5613 ci.description = top.thumbHolder.lastDescription;
5614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005615 ci.numActivities = numActivities;
5616 ci.numRunning = numRunning;
5617 //System.out.println(
5618 // "#" + maxNum + ": " + " descr=" + ci.description);
5619 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005620 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 TAG, "State=" + top.state + "Idle=" + top.idle
5622 + " app=" + top.app
5623 + " thr=" + (top.app != null ? top.app.thread : null));
5624 if (top.state == ActivityState.RESUMED
5625 || top.state == ActivityState.PAUSING) {
5626 if (top.idle && top.app != null
5627 && top.app.thread != null) {
5628 topRecord = top;
5629 topThumbnail = top.app.thread;
5630 } else {
5631 top.thumbnailNeeded = true;
5632 }
5633 }
5634 if (pending == null) {
5635 pending = new PendingThumbnailsRecord(receiver);
5636 }
5637 pending.pendingRecords.add(top);
5638 }
5639 list.add(ci);
5640 maxNum--;
5641 top = null;
5642 }
5643 }
5644
5645 if (pending != null) {
5646 mPendingThumbnails.add(pending);
5647 }
5648 }
5649
Joe Onorato8a9b2202010-02-26 18:56:32 -08005650 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651
5652 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005653 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005655 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005657 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005658 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 }
5660 }
5661
5662 if (pending == null && receiver != null) {
5663 // In this case all thumbnails were available and the client
5664 // is being asked to be told when the remaining ones come in...
5665 // which is unusually, since the top-most currently running
5666 // activity should never have a canned thumbnail! Oh well.
5667 try {
5668 receiver.finished();
5669 } catch (RemoteException ex) {
5670 }
5671 }
5672
5673 return list;
5674 }
5675
5676 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005677 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005678 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005679 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07005680 // Check if the caller is holding permissions for cross-user requests.
5681 if (checkComponentPermission(
5682 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5683 Binder.getCallingPid(), callingUid, -1, true)
5684 != PackageManager.PERMISSION_GRANTED) {
5685 String msg = "Permission Denial: "
5686 + "Request to get recent tasks for user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005687 + " but is calling from user " + UserHandle.getUserId(callingUid)
Amith Yamasani82644082012-08-03 13:09:11 -07005688 + "; this requires "
5689 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5690 Slog.w(TAG, msg);
5691 throw new SecurityException(msg);
5692 } else {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005693 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07005694 userId = mCurrentUserId;
5695 }
5696 }
5697 }
5698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 synchronized (this) {
5700 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5701 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005702 final boolean detailed = checkCallingPermission(
5703 android.Manifest.permission.GET_DETAILED_TASKS)
5704 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005706 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 final int N = mRecentTasks.size();
5709 ArrayList<ActivityManager.RecentTaskInfo> res
5710 = new ArrayList<ActivityManager.RecentTaskInfo>(
5711 maxNum < N ? maxNum : N);
5712 for (int i=0; i<N && maxNum > 0; i++) {
5713 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005714 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005715 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005716 // Return the entry if desired by the caller. We always return
5717 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005718 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005719 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5720 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005721
Dianne Hackborn905577f2011-09-07 18:31:28 -07005722 if (i == 0
5723 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 || (tr.intent == null)
5725 || ((tr.intent.getFlags()
5726 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5727 ActivityManager.RecentTaskInfo rti
5728 = new ActivityManager.RecentTaskInfo();
5729 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005730 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 rti.baseIntent = new Intent(
5732 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005733 if (!detailed) {
5734 rti.baseIntent.replaceExtras((Bundle)null);
5735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005737 rti.description = tr.lastDescription;
5738
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005739 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5740 // Check whether this activity is currently available.
5741 try {
5742 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005743 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005744 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005745 continue;
5746 }
5747 } else if (rti.baseIntent != null) {
5748 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005749 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005750 continue;
5751 }
5752 }
5753 } catch (RemoteException e) {
5754 // Will never happen.
5755 }
5756 }
5757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758 res.add(rti);
5759 maxNum--;
5760 }
5761 }
5762 return res;
5763 }
5764 }
5765
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005766 private TaskRecord taskForIdLocked(int id) {
5767 final int N = mRecentTasks.size();
5768 for (int i=0; i<N; i++) {
5769 TaskRecord tr = mRecentTasks.get(i);
5770 if (tr.taskId == id) {
5771 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005772 }
5773 }
5774 return null;
5775 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005776
5777 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5778 synchronized (this) {
5779 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5780 "getTaskThumbnails()");
5781 TaskRecord tr = taskForIdLocked(id);
5782 if (tr != null) {
5783 return mMainStack.getTaskThumbnailsLocked(tr);
5784 }
5785 }
5786 return null;
5787 }
5788
5789 public boolean removeSubTask(int taskId, int subTaskIndex) {
5790 synchronized (this) {
5791 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5792 "removeSubTask()");
5793 long ident = Binder.clearCallingIdentity();
5794 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005795 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5796 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005797 } finally {
5798 Binder.restoreCallingIdentity(ident);
5799 }
5800 }
5801 }
5802
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005803 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5804 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005805 Intent baseIntent = new Intent(
5806 tr.intent != null ? tr.intent : tr.affinityIntent);
5807 ComponentName component = baseIntent.getComponent();
5808 if (component == null) {
5809 Slog.w(TAG, "Now component for base intent of task: " + tr);
5810 return;
5811 }
5812
5813 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005814 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005815
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005816 if (killProcesses) {
5817 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005818 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005819 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005820 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5821 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5822 for (int i=0; i<uids.size(); i++) {
5823 ProcessRecord proc = uids.valueAt(i);
5824 if (proc.userId != tr.userId) {
5825 continue;
5826 }
5827 if (!proc.pkgList.contains(pkg)) {
5828 continue;
5829 }
5830 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005831 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005832 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005833
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005834 // Kill the running processes.
5835 for (int i=0; i<procs.size(); i++) {
5836 ProcessRecord pr = procs.get(i);
5837 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5838 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5839 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5840 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005841 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005842 Process.killProcessQuiet(pr.pid);
5843 } else {
5844 pr.waitingToKill = "remove task";
5845 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005846 }
5847 }
5848 }
5849
5850 public boolean removeTask(int taskId, int flags) {
5851 synchronized (this) {
5852 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5853 "removeTask()");
5854 long ident = Binder.clearCallingIdentity();
5855 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005856 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5857 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005858 if (r != null) {
5859 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005860 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005861 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005862 } else {
5863 TaskRecord tr = null;
5864 int i=0;
5865 while (i < mRecentTasks.size()) {
5866 TaskRecord t = mRecentTasks.get(i);
5867 if (t.taskId == taskId) {
5868 tr = t;
5869 break;
5870 }
5871 i++;
5872 }
5873 if (tr != null) {
5874 if (tr.numActivities <= 0) {
5875 // Caller is just removing a recent task that is
5876 // not actively running. That is easy!
5877 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005878 cleanUpRemovedTaskLocked(tr, flags);
5879 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005880 } else {
5881 Slog.w(TAG, "removeTask: task " + taskId
5882 + " does not have activities to remove, "
5883 + " but numActivities=" + tr.numActivities
5884 + ": " + tr);
5885 }
5886 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005887 }
5888 } finally {
5889 Binder.restoreCallingIdentity(ident);
5890 }
5891 }
5892 return false;
5893 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005895 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5896 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005897 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005898 TaskRecord jt = startTask;
5899
5900 // First look backwards
5901 for (j=startIndex-1; j>=0; 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 jt = r.task;
5905 if (affinity.equals(jt.affinity)) {
5906 return j;
5907 }
5908 }
5909 }
5910
5911 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005912 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005913 jt = startTask;
5914 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005915 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005916 if (r.task != jt) {
5917 if (affinity.equals(jt.affinity)) {
5918 return j;
5919 }
5920 jt = r.task;
5921 }
5922 }
5923
5924 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005925 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005926 return N-1;
5927 }
5928
5929 return -1;
5930 }
5931
5932 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005933 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005935 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005936 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5937 "moveTaskToFront()");
5938
5939 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005940 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5941 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005942 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005943 return;
5944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 final long origId = Binder.clearCallingIdentity();
5946 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005947 TaskRecord tr = taskForIdLocked(task);
5948 if (tr != null) {
5949 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5950 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005952 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5953 // Caller wants the home activity moved with it. To accomplish this,
5954 // we'll just move the home task to the top first.
5955 mMainStack.moveHomeToFrontLocked();
5956 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005957 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005958 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005960 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5961 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005962 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005963 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5964 mMainStack.mUserLeaving = true;
5965 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005966 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5967 // Caller wants the home activity moved with it. To accomplish this,
5968 // we'll just move the home task to the top first.
5969 mMainStack.moveHomeToFrontLocked();
5970 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005971 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 return;
5973 }
5974 }
5975 } finally {
5976 Binder.restoreCallingIdentity(origId);
5977 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005978 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005979 }
5980 }
5981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 public void moveTaskToBack(int task) {
5983 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5984 "moveTaskToBack()");
5985
5986 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005987 if (mMainStack.mResumedActivity != null
5988 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005989 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5990 Binder.getCallingUid(), "Task to back")) {
5991 return;
5992 }
5993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005995 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 Binder.restoreCallingIdentity(origId);
5997 }
5998 }
5999
6000 /**
6001 * Moves an activity, and all of the other activities within the same task, to the bottom
6002 * of the history stack. The activity's order within the task is unchanged.
6003 *
6004 * @param token A reference to the activity we wish to move
6005 * @param nonRoot If false then this only works if the activity is the root
6006 * of a task; if true it will work for any activity in a task.
6007 * @return Returns true if the move completed, false if not.
6008 */
6009 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006010 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006011 synchronized(this) {
6012 final long origId = Binder.clearCallingIdentity();
6013 int taskId = getTaskForActivityLocked(token, !nonRoot);
6014 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006015 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006016 }
6017 Binder.restoreCallingIdentity(origId);
6018 }
6019 return false;
6020 }
6021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 public void moveTaskBackwards(int task) {
6023 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
6024 "moveTaskBackwards()");
6025
6026 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07006027 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
6028 Binder.getCallingUid(), "Task backwards")) {
6029 return;
6030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 final long origId = Binder.clearCallingIdentity();
6032 moveTaskBackwardsLocked(task);
6033 Binder.restoreCallingIdentity(origId);
6034 }
6035 }
6036
6037 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006038 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 }
6040
6041 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
6042 synchronized(this) {
6043 return getTaskForActivityLocked(token, onlyRoot);
6044 }
6045 }
6046
6047 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006048 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006049 TaskRecord lastTask = null;
6050 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006051 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08006052 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006053 if (!onlyRoot || lastTask != r.task) {
6054 return r.task.taskId;
6055 }
6056 return -1;
6057 }
6058 lastTask = r.task;
6059 }
6060
6061 return -1;
6062 }
6063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 // =========================================================
6065 // THUMBNAILS
6066 // =========================================================
6067
6068 public void reportThumbnail(IBinder token,
6069 Bitmap thumbnail, CharSequence description) {
6070 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
6071 final long origId = Binder.clearCallingIdentity();
6072 sendPendingThumbnail(null, token, thumbnail, description, true);
6073 Binder.restoreCallingIdentity(origId);
6074 }
6075
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006076 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 Bitmap thumbnail, CharSequence description, boolean always) {
6078 TaskRecord task = null;
6079 ArrayList receivers = null;
6080
6081 //System.out.println("Send pending thumbnail: " + r);
6082
6083 synchronized(this) {
6084 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006085 r = mMainStack.isInStackLocked(token);
6086 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087 return;
6088 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006090 if (thumbnail == null && r.thumbHolder != null) {
6091 thumbnail = r.thumbHolder.lastThumbnail;
6092 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 }
6094 if (thumbnail == null && !always) {
6095 // If there is no thumbnail, and this entry is not actually
6096 // going away, then abort for now and pick up the next
6097 // thumbnail we get.
6098 return;
6099 }
6100 task = r.task;
6101
6102 int N = mPendingThumbnails.size();
6103 int i=0;
6104 while (i<N) {
6105 PendingThumbnailsRecord pr =
6106 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6107 //System.out.println("Looking in " + pr.pendingRecords);
6108 if (pr.pendingRecords.remove(r)) {
6109 if (receivers == null) {
6110 receivers = new ArrayList();
6111 }
6112 receivers.add(pr);
6113 if (pr.pendingRecords.size() == 0) {
6114 pr.finished = true;
6115 mPendingThumbnails.remove(i);
6116 N--;
6117 continue;
6118 }
6119 }
6120 i++;
6121 }
6122 }
6123
6124 if (receivers != null) {
6125 final int N = receivers.size();
6126 for (int i=0; i<N; i++) {
6127 try {
6128 PendingThumbnailsRecord pr =
6129 (PendingThumbnailsRecord)receivers.get(i);
6130 pr.receiver.newThumbnail(
6131 task != null ? task.taskId : -1, thumbnail, description);
6132 if (pr.finished) {
6133 pr.receiver.finished();
6134 }
6135 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006136 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 }
6138 }
6139 }
6140 }
6141
6142 // =========================================================
6143 // CONTENT PROVIDERS
6144 // =========================================================
6145
Jeff Brown10e89712011-07-08 18:52:57 -07006146 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6147 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006149 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006150 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006151 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 } catch (RemoteException ex) {
6153 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006154 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006155 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6156 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006158 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006159 for (int i=0; i<N; i++) {
6160 ProviderInfo cpi =
6161 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006162 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6163 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006164 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006165 // This is a singleton provider, but a user besides the
6166 // default user is asking to initialize a process it runs
6167 // in... well, no, it doesn't actually run in this process,
6168 // it runs in the process of the default user. Get rid of it.
6169 providers.remove(i);
6170 N--;
6171 continue;
6172 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006173
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006174 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006175 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006176 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006177 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006178 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006180 if (DEBUG_MU)
6181 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 app.pubProviders.put(cpi.name, cpr);
6183 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006184 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 }
6186 }
6187 return providers;
6188 }
6189
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006190 /**
6191 * Check if {@link ProcessRecord} has a possible chance at accessing the
6192 * given {@link ProviderInfo}. Final permission checking is always done
6193 * in {@link ContentProvider}.
6194 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006195 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006196 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006198 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006200 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006201 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 return null;
6203 }
6204 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006205 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 == PackageManager.PERMISSION_GRANTED) {
6207 return null;
6208 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006209
6210 PathPermission[] pps = cpi.pathPermissions;
6211 if (pps != null) {
6212 int i = pps.length;
6213 while (i > 0) {
6214 i--;
6215 PathPermission pp = pps[i];
6216 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006217 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006218 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006219 return null;
6220 }
6221 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006222 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006223 == PackageManager.PERMISSION_GRANTED) {
6224 return null;
6225 }
6226 }
6227 }
6228
Dianne Hackbornb424b632010-08-18 15:59:05 -07006229 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6230 if (perms != null) {
6231 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6232 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6233 return null;
6234 }
6235 }
6236 }
6237
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006238 String msg;
6239 if (!cpi.exported) {
6240 msg = "Permission Denial: opening provider " + cpi.name
6241 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6242 + ", uid=" + callingUid + ") that is not exported from uid "
6243 + cpi.applicationInfo.uid;
6244 } else {
6245 msg = "Permission Denial: opening provider " + cpi.name
6246 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6247 + ", uid=" + callingUid + ") requires "
6248 + cpi.readPermission + " or " + cpi.writePermission;
6249 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006250 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 return msg;
6252 }
6253
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006254 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6255 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006256 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006257 for (int i=0; i<r.conProviders.size(); i++) {
6258 ContentProviderConnection conn = r.conProviders.get(i);
6259 if (conn.provider == cpr) {
6260 if (DEBUG_PROVIDER) Slog.v(TAG,
6261 "Adding provider requested by "
6262 + r.processName + " from process "
6263 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6264 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6265 if (stable) {
6266 conn.stableCount++;
6267 conn.numStableIncs++;
6268 } else {
6269 conn.unstableCount++;
6270 conn.numUnstableIncs++;
6271 }
6272 return conn;
6273 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006274 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006275 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6276 if (stable) {
6277 conn.stableCount = 1;
6278 conn.numStableIncs = 1;
6279 } else {
6280 conn.unstableCount = 1;
6281 conn.numUnstableIncs = 1;
6282 }
6283 cpr.connections.add(conn);
6284 r.conProviders.add(conn);
6285 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006286 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006287 cpr.addExternalProcessHandleLocked(externalProcessToken);
6288 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006289 }
6290
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006291 boolean decProviderCountLocked(ContentProviderConnection conn,
6292 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6293 if (conn != null) {
6294 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006295 if (DEBUG_PROVIDER) Slog.v(TAG,
6296 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006297 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006298 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006299 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6300 if (stable) {
6301 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006302 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006303 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006304 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006305 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6306 cpr.connections.remove(conn);
6307 conn.client.conProviders.remove(conn);
6308 return true;
6309 }
6310 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006311 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006312 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006313 return false;
6314 }
6315
Amith Yamasani742a6712011-05-04 14:49:28 -07006316 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006317 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006319 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 ProviderInfo cpi = null;
6321
6322 synchronized(this) {
6323 ProcessRecord r = null;
6324 if (caller != null) {
6325 r = getRecordForAppLocked(caller);
6326 if (r == null) {
6327 throw new SecurityException(
6328 "Unable to find app for caller " + caller
6329 + " (pid=" + Binder.getCallingPid()
6330 + ") when getting content provider " + name);
6331 }
Dianne Hackborn41203752012-08-31 14:05:51 -07006332 if (r.userId != userId) {
6333 throw new SecurityException("Calling requested user " + userId
6334 + " but app is user " + r.userId);
6335 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 }
6337
6338 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006339 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006340 boolean providerRunning = cpr != null;
6341 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006343 String msg;
6344 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6345 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 }
6347
6348 if (r != null && cpr.canRunHere(r)) {
6349 // This provider has been published or is in the process
6350 // of being published... but it is also allowed to run
6351 // in the caller's process, so don't make a connection
6352 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006353 ContentProviderHolder holder = cpr.newHolder(null);
6354 // don't give caller the provider object, it needs
6355 // to make its own.
6356 holder.provider = null;
6357 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 }
6359
6360 final long origId = Binder.clearCallingIdentity();
6361
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006362 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006364 conn = incProviderCountLocked(r, cpr, token, stable);
6365 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006366 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006367 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006368 // make sure to count it as being accessed and thus
6369 // back up on the LRU list. This is good because
6370 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006371 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006372 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006373 }
6374
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006375 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006376 if (false) {
6377 if (cpr.name.flattenToShortString().equals(
6378 "com.android.providers.calendar/.CalendarProvider2")) {
6379 Slog.v(TAG, "****************** KILLING "
6380 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006381 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006382 }
6383 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006384 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006385 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6386 // NOTE: there is still a race here where a signal could be
6387 // pending on the process even though we managed to update its
6388 // adj level. Not sure what to do about this, but at least
6389 // the race is now smaller.
6390 if (!success) {
6391 // Uh oh... it looks like the provider's process
6392 // has been killed on us. We need to wait for a new
6393 // process to be started, and make sure its death
6394 // doesn't kill our process.
6395 Slog.i(TAG,
6396 "Existing provider " + cpr.name.flattenToShortString()
6397 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006398 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006399 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006400 if (!lastRef) {
6401 // This wasn't the last ref our process had on
6402 // the provider... we have now been killed, bail.
6403 return null;
6404 }
6405 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006406 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 }
6409
6410 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006413 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006414 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006416 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006417 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006418 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 } catch (RemoteException ex) {
6420 }
6421 if (cpi == null) {
6422 return null;
6423 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006424 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6425 cpi.name, cpi.flags);
6426 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006427 userId = 0;
6428 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006429 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006430
Dianne Hackbornb424b632010-08-18 15:59:05 -07006431 String msg;
6432 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6433 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 }
6435
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006436 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006437 && !cpi.processName.equals("system")) {
6438 // If this content provider does not run in the system
6439 // process, and the system is not yet ready to run other
6440 // processes, then fail fast instead of hanging.
6441 throw new IllegalArgumentException(
6442 "Attempt to launch content provider before system ready");
6443 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006444
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006445 // Make sure that the user who owns this provider is started. If not,
6446 // we don't want to allow it to run.
6447 if (mStartedUsers.get(userId) == null) {
6448 Slog.w(TAG, "Unable to launch app "
6449 + cpi.applicationInfo.packageName + "/"
6450 + cpi.applicationInfo.uid + " for provider "
6451 + name + ": user " + userId + " is stopped");
6452 return null;
6453 }
6454
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006455 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006456 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 final boolean firstClass = cpr == null;
6458 if (firstClass) {
6459 try {
6460 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006461 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 getApplicationInfo(
6463 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006464 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006465 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006466 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 + cpi.name);
6468 return null;
6469 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006470 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006471 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472 } catch (RemoteException ex) {
6473 // pm is in same process, this will never happen.
6474 }
6475 }
6476
6477 if (r != null && cpr.canRunHere(r)) {
6478 // If this is a multiprocess provider, then just return its
6479 // info and allow the caller to instantiate it. Only do
6480 // this if the provider is the same user as the caller's
6481 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006482 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 }
6484
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006485 if (DEBUG_PROVIDER) {
6486 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006487 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006488 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 }
6490
6491 // This is single process, and our app is now connecting to it.
6492 // See if we are already in the process of launching this
6493 // provider.
6494 final int N = mLaunchingProviders.size();
6495 int i;
6496 for (i=0; i<N; i++) {
6497 if (mLaunchingProviders.get(i) == cpr) {
6498 break;
6499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006500 }
6501
6502 // If the provider is not already being launched, then get it
6503 // started.
6504 if (i >= N) {
6505 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006506
6507 try {
6508 // Content provider is now in use, its package can't be stopped.
6509 try {
6510 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006511 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006512 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006513 } catch (IllegalArgumentException e) {
6514 Slog.w(TAG, "Failed trying to unstop package "
6515 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006516 }
6517
6518 ProcessRecord proc = startProcessLocked(cpi.processName,
6519 cpr.appInfo, false, 0, "content provider",
6520 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006521 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006522 if (proc == null) {
6523 Slog.w(TAG, "Unable to launch app "
6524 + cpi.applicationInfo.packageName + "/"
6525 + cpi.applicationInfo.uid + " for provider "
6526 + name + ": process is bad");
6527 return null;
6528 }
6529 cpr.launchingApp = proc;
6530 mLaunchingProviders.add(cpr);
6531 } finally {
6532 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006534 }
6535
6536 // Make sure the provider is published (the same provider class
6537 // may be published under multiple names).
6538 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006539 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006541
Amith Yamasani742a6712011-05-04 14:49:28 -07006542 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006543 conn = incProviderCountLocked(r, cpr, token, stable);
6544 if (conn != null) {
6545 conn.waiting = true;
6546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006547 }
6548 }
6549
6550 // Wait for the provider to be published...
6551 synchronized (cpr) {
6552 while (cpr.provider == null) {
6553 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006554 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006555 + cpi.applicationInfo.packageName + "/"
6556 + cpi.applicationInfo.uid + " for provider "
6557 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006558 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559 cpi.applicationInfo.packageName,
6560 cpi.applicationInfo.uid, name);
6561 return null;
6562 }
6563 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006564 if (DEBUG_MU) {
6565 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6566 + cpr.launchingApp);
6567 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006568 if (conn != null) {
6569 conn.waiting = true;
6570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006571 cpr.wait();
6572 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006573 } finally {
6574 if (conn != null) {
6575 conn.waiting = false;
6576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006577 }
6578 }
6579 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006580 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006581 }
6582
6583 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006584 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006585 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 if (caller == null) {
6587 String msg = "null IApplicationThread when getting content provider "
6588 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006589 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 throw new SecurityException(msg);
6591 }
6592
Dianne Hackborn41203752012-08-31 14:05:51 -07006593 return getContentProviderImpl(caller, name, null, stable,
6594 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 }
6596
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006597 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6598 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6599 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006600 return getContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006601 }
6602
Dianne Hackborn41203752012-08-31 14:05:51 -07006603 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6604 IBinder token, int userId) {
6605 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 }
6607
6608 /**
6609 * Drop a content provider from a ProcessRecord's bookkeeping
6610 * @param cpr
6611 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006612 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006613 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006615 ContentProviderConnection conn;
6616 try {
6617 conn = (ContentProviderConnection)connection;
6618 } catch (ClassCastException e) {
6619 String msg ="removeContentProvider: " + connection
6620 + " not a ContentProviderConnection";
6621 Slog.w(TAG, msg);
6622 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006623 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006624 if (conn == null) {
6625 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006626 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006627 if (decProviderCountLocked(conn, null, null, stable)) {
6628 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006630 }
6631 }
6632
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006633 public void removeContentProviderExternal(String name, IBinder token) {
6634 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6635 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006636 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006637 }
6638
Dianne Hackborn41203752012-08-31 14:05:51 -07006639 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006640 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006641 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006642 if(cpr == null) {
6643 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006644 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006645 return;
6646 }
6647
6648 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006649 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006650 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006651 if (localCpr.hasExternalProcessHandles()) {
6652 if (localCpr.removeExternalProcessHandleLocked(token)) {
6653 updateOomAdjLocked();
6654 } else {
6655 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6656 + " with no external reference for token: "
6657 + token + ".");
6658 }
6659 } else {
6660 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6661 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006662 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 }
6664 }
6665
6666 public final void publishContentProviders(IApplicationThread caller,
6667 List<ContentProviderHolder> providers) {
6668 if (providers == null) {
6669 return;
6670 }
6671
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006672 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006673 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006674 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006675 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006676 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677 if (r == null) {
6678 throw new SecurityException(
6679 "Unable to find app for caller " + caller
6680 + " (pid=" + Binder.getCallingPid()
6681 + ") when publishing content providers");
6682 }
6683
6684 final long origId = Binder.clearCallingIdentity();
6685
6686 final int N = providers.size();
6687 for (int i=0; i<N; i++) {
6688 ContentProviderHolder src = providers.get(i);
6689 if (src == null || src.info == null || src.provider == null) {
6690 continue;
6691 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006692 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006693 if (DEBUG_MU)
6694 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006696 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006697 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006698 String names[] = dst.info.authority.split(";");
6699 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006700 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 }
6702
6703 int NL = mLaunchingProviders.size();
6704 int j;
6705 for (j=0; j<NL; j++) {
6706 if (mLaunchingProviders.get(j) == dst) {
6707 mLaunchingProviders.remove(j);
6708 j--;
6709 NL--;
6710 }
6711 }
6712 synchronized (dst) {
6713 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006714 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 dst.notifyAll();
6716 }
6717 updateOomAdjLocked(r);
6718 }
6719 }
6720
6721 Binder.restoreCallingIdentity(origId);
6722 }
6723 }
6724
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006725 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6726 ContentProviderConnection conn;
6727 try {
6728 conn = (ContentProviderConnection)connection;
6729 } catch (ClassCastException e) {
6730 String msg ="refContentProvider: " + connection
6731 + " not a ContentProviderConnection";
6732 Slog.w(TAG, msg);
6733 throw new IllegalArgumentException(msg);
6734 }
6735 if (conn == null) {
6736 throw new NullPointerException("connection is null");
6737 }
6738
6739 synchronized (this) {
6740 if (stable > 0) {
6741 conn.numStableIncs += stable;
6742 }
6743 stable = conn.stableCount + stable;
6744 if (stable < 0) {
6745 throw new IllegalStateException("stableCount < 0: " + stable);
6746 }
6747
6748 if (unstable > 0) {
6749 conn.numUnstableIncs += unstable;
6750 }
6751 unstable = conn.unstableCount + unstable;
6752 if (unstable < 0) {
6753 throw new IllegalStateException("unstableCount < 0: " + unstable);
6754 }
6755
6756 if ((stable+unstable) <= 0) {
6757 throw new IllegalStateException("ref counts can't go to zero here: stable="
6758 + stable + " unstable=" + unstable);
6759 }
6760 conn.stableCount = stable;
6761 conn.unstableCount = unstable;
6762 return !conn.dead;
6763 }
6764 }
6765
6766 public void unstableProviderDied(IBinder connection) {
6767 ContentProviderConnection conn;
6768 try {
6769 conn = (ContentProviderConnection)connection;
6770 } catch (ClassCastException e) {
6771 String msg ="refContentProvider: " + connection
6772 + " not a ContentProviderConnection";
6773 Slog.w(TAG, msg);
6774 throw new IllegalArgumentException(msg);
6775 }
6776 if (conn == null) {
6777 throw new NullPointerException("connection is null");
6778 }
6779
6780 // Safely retrieve the content provider associated with the connection.
6781 IContentProvider provider;
6782 synchronized (this) {
6783 provider = conn.provider.provider;
6784 }
6785
6786 if (provider == null) {
6787 // Um, yeah, we're way ahead of you.
6788 return;
6789 }
6790
6791 // Make sure the caller is being honest with us.
6792 if (provider.asBinder().pingBinder()) {
6793 // Er, no, still looks good to us.
6794 synchronized (this) {
6795 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6796 + " says " + conn + " died, but we don't agree");
6797 return;
6798 }
6799 }
6800
6801 // Well look at that! It's dead!
6802 synchronized (this) {
6803 if (conn.provider.provider != provider) {
6804 // But something changed... good enough.
6805 return;
6806 }
6807
6808 ProcessRecord proc = conn.provider.proc;
6809 if (proc == null || proc.thread == null) {
6810 // Seems like the process is already cleaned up.
6811 return;
6812 }
6813
6814 // As far as we're concerned, this is just like receiving a
6815 // death notification... just a bit prematurely.
6816 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6817 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006818 final long ident = Binder.clearCallingIdentity();
6819 try {
6820 appDiedLocked(proc, proc.pid, proc.thread);
6821 } finally {
6822 Binder.restoreCallingIdentity(ident);
6823 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006824 }
6825 }
6826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006827 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006828 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006829 synchronized (mSelf) {
6830 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6831 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006832 if (providers != null) {
6833 for (int i=providers.size()-1; i>=0; i--) {
6834 ProviderInfo pi = (ProviderInfo)providers.get(i);
6835 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6836 Slog.w(TAG, "Not installing system proc provider " + pi.name
6837 + ": not system .apk");
6838 providers.remove(i);
6839 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006840 }
6841 }
6842 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006843 if (providers != null) {
6844 mSystemThread.installSystemProviders(providers);
6845 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006846
6847 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006848
6849 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006850 }
6851
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006852 /**
6853 * Allows app to retrieve the MIME type of a URI without having permission
6854 * to access its content provider.
6855 *
6856 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6857 *
6858 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6859 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6860 */
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006861 public String getProviderMimeType(Uri uri, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006862 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07006863 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
6864 userId, false, true, "getProviderMimeType", null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006865 final String name = uri.getAuthority();
6866 final long ident = Binder.clearCallingIdentity();
6867 ContentProviderHolder holder = null;
6868
6869 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006870 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006871 if (holder != null) {
6872 return holder.provider.getType(uri);
6873 }
6874 } catch (RemoteException e) {
6875 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6876 return null;
6877 } finally {
6878 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006879 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006880 }
6881 Binder.restoreCallingIdentity(ident);
6882 }
6883
6884 return null;
6885 }
6886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006887 // =========================================================
6888 // GLOBAL MANAGEMENT
6889 // =========================================================
6890
6891 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006892 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006893 String proc = customProcess != null ? customProcess : info.processName;
6894 BatteryStatsImpl.Uid.Proc ps = null;
6895 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006896 int uid = info.uid;
6897 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006898 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006899 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6900 uid = 0;
6901 while (true) {
6902 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6903 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6904 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6905 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006906 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006907 mNextIsolatedProcessUid++;
6908 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6909 // No process for this uid, use it.
6910 break;
6911 }
6912 stepsLeft--;
6913 if (stepsLeft <= 0) {
6914 return null;
6915 }
6916 }
6917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006918 synchronized (stats) {
6919 ps = stats.getProcessStatsLocked(info.uid, proc);
6920 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006921 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006922 }
6923
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006924 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6925 ProcessRecord app;
6926 if (!isolated) {
6927 app = getProcessRecordLocked(info.processName, info.uid);
6928 } else {
6929 app = null;
6930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006931
6932 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006933 app = newProcessRecordLocked(null, info, null, isolated);
6934 mProcessNames.put(info.processName, app.uid, app);
6935 if (isolated) {
6936 mIsolatedProcesses.put(app.uid, app);
6937 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006938 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006939 }
6940
Dianne Hackborne7f97212011-02-24 14:40:20 -08006941 // This package really, really can not be stopped.
6942 try {
6943 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006944 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006945 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006946 } catch (IllegalArgumentException e) {
6947 Slog.w(TAG, "Failed trying to unstop package "
6948 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006949 }
6950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6952 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6953 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006954 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006955 }
6956 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6957 mPersistentStartingProcesses.add(app);
6958 startProcessLocked(app, "added application", app.processName);
6959 }
6960
6961 return app;
6962 }
6963
6964 public void unhandledBack() {
6965 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6966 "unhandledBack()");
6967
6968 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006969 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006970 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006971 TAG, "Performing unhandledBack(): stack size = " + count);
6972 if (count > 1) {
6973 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006974 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006975 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6976 Binder.restoreCallingIdentity(origId);
6977 }
6978 }
6979 }
6980
6981 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006982 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07006983 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006984 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07006985 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006986 ParcelFileDescriptor pfd = null;
6987 if (cph != null) {
6988 // We record the binder invoker's uid in thread-local storage before
6989 // going to the content provider to open the file. Later, in the code
6990 // that handles all permissions checks, we look for this uid and use
6991 // that rather than the Activity Manager's own uid. The effect is that
6992 // we do the check against the caller's permissions even though it looks
6993 // to the content provider like the Activity Manager itself is making
6994 // the request.
6995 sCallerIdentity.set(new Identity(
6996 Binder.getCallingPid(), Binder.getCallingUid()));
6997 try {
6998 pfd = cph.provider.openFile(uri, "r");
6999 } catch (FileNotFoundException e) {
7000 // do nothing; pfd will be returned null
7001 } finally {
7002 // Ensure that whatever happens, we clean up the identity state
7003 sCallerIdentity.remove();
7004 }
7005
7006 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07007007 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007008 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007009 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007010 }
7011 return pfd;
7012 }
7013
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007014 // Actually is sleeping or shutting down or whatever else in the future
7015 // is an inactive state.
7016 public boolean isSleeping() {
7017 return mSleeping || mShuttingDown;
7018 }
7019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007020 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007021 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7022 != PackageManager.PERMISSION_GRANTED) {
7023 throw new SecurityException("Requires permission "
7024 + android.Manifest.permission.DEVICE_POWER);
7025 }
7026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007028 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007029 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007030
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007031 if (!mSleeping) {
7032 mSleeping = true;
7033 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07007034
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007035 // Initialize the wake times of all processes.
7036 checkExcessivePowerUsageLocked(false);
7037 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7038 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
7039 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
7040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 }
7042 }
7043
Dianne Hackborn55280a92009-05-07 15:53:46 -07007044 public boolean shutdown(int timeout) {
7045 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
7046 != PackageManager.PERMISSION_GRANTED) {
7047 throw new SecurityException("Requires permission "
7048 + android.Manifest.permission.SHUTDOWN);
7049 }
7050
7051 boolean timedout = false;
7052
7053 synchronized(this) {
7054 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07007055 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007056
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007057 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007058 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07007059 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007060 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08007061 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07007062 long delay = endTime - System.currentTimeMillis();
7063 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007064 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07007065 timedout = true;
7066 break;
7067 }
7068 try {
7069 this.wait();
7070 } catch (InterruptedException e) {
7071 }
7072 }
7073 }
7074 }
7075
7076 mUsageStatsService.shutdown();
7077 mBatteryStatsService.shutdown();
7078
7079 return timedout;
7080 }
7081
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007082 public final void activitySlept(IBinder token) {
7083 if (localLOGV) Slog.v(
7084 TAG, "Activity slept: token=" + token);
7085
7086 ActivityRecord r = null;
7087
7088 final long origId = Binder.clearCallingIdentity();
7089
7090 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007091 r = mMainStack.isInStackLocked(token);
7092 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007093 mMainStack.activitySleptLocked(r);
7094 }
7095 }
7096
7097 Binder.restoreCallingIdentity(origId);
7098 }
7099
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007100 private void comeOutOfSleepIfNeededLocked() {
7101 if (!mWentToSleep && !mLockScreenShown) {
7102 if (mSleeping) {
7103 mSleeping = false;
7104 mMainStack.awakeFromSleepingLocked();
7105 mMainStack.resumeTopActivityLocked(null);
7106 }
7107 }
7108 }
7109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007110 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007111 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7112 != PackageManager.PERMISSION_GRANTED) {
7113 throw new SecurityException("Requires permission "
7114 + android.Manifest.permission.DEVICE_POWER);
7115 }
7116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007118 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007119 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007120 comeOutOfSleepIfNeededLocked();
7121 }
7122 }
7123
Jeff Brownc042ee22012-05-08 13:03:42 -07007124 private void updateEventDispatchingLocked() {
7125 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7126 }
7127
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007128 public void setLockScreenShown(boolean shown) {
7129 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7130 != PackageManager.PERMISSION_GRANTED) {
7131 throw new SecurityException("Requires permission "
7132 + android.Manifest.permission.DEVICE_POWER);
7133 }
7134
7135 synchronized(this) {
7136 mLockScreenShown = shown;
7137 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007138 }
7139 }
7140
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007141 public void stopAppSwitches() {
7142 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7143 != PackageManager.PERMISSION_GRANTED) {
7144 throw new SecurityException("Requires permission "
7145 + android.Manifest.permission.STOP_APP_SWITCHES);
7146 }
7147
7148 synchronized(this) {
7149 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7150 + APP_SWITCH_DELAY_TIME;
7151 mDidAppSwitch = false;
7152 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7153 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7154 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7155 }
7156 }
7157
7158 public void resumeAppSwitches() {
7159 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7160 != PackageManager.PERMISSION_GRANTED) {
7161 throw new SecurityException("Requires permission "
7162 + android.Manifest.permission.STOP_APP_SWITCHES);
7163 }
7164
7165 synchronized(this) {
7166 // Note that we don't execute any pending app switches... we will
7167 // let those wait until either the timeout, or the next start
7168 // activity request.
7169 mAppSwitchesAllowedTime = 0;
7170 }
7171 }
7172
7173 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7174 String name) {
7175 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7176 return true;
7177 }
7178
7179 final int perm = checkComponentPermission(
7180 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007181 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007182 if (perm == PackageManager.PERMISSION_GRANTED) {
7183 return true;
7184 }
7185
Joe Onorato8a9b2202010-02-26 18:56:32 -08007186 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007187 return false;
7188 }
7189
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 public void setDebugApp(String packageName, boolean waitForDebugger,
7191 boolean persistent) {
7192 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7193 "setDebugApp()");
7194
7195 // Note that this is not really thread safe if there are multiple
7196 // callers into it at the same time, but that's not a situation we
7197 // care about.
7198 if (persistent) {
7199 final ContentResolver resolver = mContext.getContentResolver();
7200 Settings.System.putString(
7201 resolver, Settings.System.DEBUG_APP,
7202 packageName);
7203 Settings.System.putInt(
7204 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7205 waitForDebugger ? 1 : 0);
7206 }
7207
7208 synchronized (this) {
7209 if (!persistent) {
7210 mOrigDebugApp = mDebugApp;
7211 mOrigWaitForDebugger = mWaitForDebugger;
7212 }
7213 mDebugApp = packageName;
7214 mWaitForDebugger = waitForDebugger;
7215 mDebugTransient = !persistent;
7216 if (packageName != null) {
7217 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07007218 forceStopPackageLocked(packageName, -1, false, false, true, true,
7219 UserHandle.USER_ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007220 Binder.restoreCallingIdentity(origId);
7221 }
7222 }
7223 }
7224
Siva Velusamy92a8b222012-03-09 16:24:04 -08007225 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7226 synchronized (this) {
7227 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7228 if (!isDebuggable) {
7229 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7230 throw new SecurityException("Process not debuggable: " + app.packageName);
7231 }
7232 }
7233
7234 mOpenGlTraceApp = processName;
7235 }
7236 }
7237
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007238 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7239 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7240 synchronized (this) {
7241 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7242 if (!isDebuggable) {
7243 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7244 throw new SecurityException("Process not debuggable: " + app.packageName);
7245 }
7246 }
7247 mProfileApp = processName;
7248 mProfileFile = profileFile;
7249 if (mProfileFd != null) {
7250 try {
7251 mProfileFd.close();
7252 } catch (IOException e) {
7253 }
7254 mProfileFd = null;
7255 }
7256 mProfileFd = profileFd;
7257 mProfileType = 0;
7258 mAutoStopProfiler = autoStopProfiler;
7259 }
7260 }
7261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007262 public void setAlwaysFinish(boolean enabled) {
7263 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7264 "setAlwaysFinish()");
7265
7266 Settings.System.putInt(
7267 mContext.getContentResolver(),
7268 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7269
7270 synchronized (this) {
7271 mAlwaysFinishActivities = enabled;
7272 }
7273 }
7274
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007275 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007276 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007277 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007278 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007279 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007280 }
7281 }
7282
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007283 public boolean isUserAMonkey() {
7284 // For now the fact that there is a controller implies
7285 // we have a monkey.
7286 synchronized (this) {
7287 return mController != null;
7288 }
7289 }
7290
Jeff Sharkeya4620792011-05-20 15:29:23 -07007291 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007292 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7293 "registerProcessObserver()");
7294 synchronized (this) {
7295 mProcessObservers.register(observer);
7296 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007297 }
7298
7299 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007300 synchronized (this) {
7301 mProcessObservers.unregister(observer);
7302 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007303 }
7304
Daniel Sandler69a48172010-06-23 16:29:36 -04007305 public void setImmersive(IBinder token, boolean immersive) {
7306 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007307 ActivityRecord r = mMainStack.isInStackLocked(token);
7308 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007309 throw new IllegalArgumentException();
7310 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007311 r.immersive = immersive;
7312 }
7313 }
7314
7315 public boolean isImmersive(IBinder token) {
7316 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007317 ActivityRecord r = mMainStack.isInStackLocked(token);
7318 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007319 throw new IllegalArgumentException();
7320 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007321 return r.immersive;
7322 }
7323 }
7324
7325 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007326 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007327 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007328 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007329 return (r != null) ? r.immersive : false;
7330 }
7331 }
7332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007333 public final void enterSafeMode() {
7334 synchronized(this) {
7335 // It only makes sense to do this before the system is ready
7336 // and started launching other packages.
7337 if (!mSystemReady) {
7338 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007339 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007340 } catch (RemoteException e) {
7341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007342 }
7343 }
7344 }
7345
Jeff Brownb09abc12011-01-13 21:08:27 -08007346 public final void showSafeModeOverlay() {
7347 View v = LayoutInflater.from(mContext).inflate(
7348 com.android.internal.R.layout.safe_mode, null);
7349 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7350 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7351 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7352 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007353 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007354 lp.format = v.getBackground().getOpacity();
7355 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7356 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7357 ((WindowManager)mContext.getSystemService(
7358 Context.WINDOW_SERVICE)).addView(v, lp);
7359 }
7360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007361 public void noteWakeupAlarm(IIntentSender sender) {
7362 if (!(sender instanceof PendingIntentRecord)) {
7363 return;
7364 }
7365 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7366 synchronized (stats) {
7367 if (mBatteryStatsService.isOnBattery()) {
7368 mBatteryStatsService.enforceCallingPermission();
7369 PendingIntentRecord rec = (PendingIntentRecord)sender;
7370 int MY_UID = Binder.getCallingUid();
7371 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7372 BatteryStatsImpl.Uid.Pkg pkg =
7373 stats.getPackageStatsLocked(uid, rec.key.packageName);
7374 pkg.incWakeupsLocked();
7375 }
7376 }
7377 }
7378
Dianne Hackborn64825172011-03-02 21:32:58 -08007379 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007380 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007381 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007382 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007383 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007384 // XXX Note: don't acquire main activity lock here, because the window
7385 // manager calls in with its locks held.
7386
7387 boolean killed = false;
7388 synchronized (mPidsSelfLocked) {
7389 int[] types = new int[pids.length];
7390 int worstType = 0;
7391 for (int i=0; i<pids.length; i++) {
7392 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7393 if (proc != null) {
7394 int type = proc.setAdj;
7395 types[i] = type;
7396 if (type > worstType) {
7397 worstType = type;
7398 }
7399 }
7400 }
7401
Dianne Hackborn64825172011-03-02 21:32:58 -08007402 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007403 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007404 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7405 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007406 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007407 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007408
7409 // If this is not a secure call, don't let it kill processes that
7410 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007411 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7412 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007413 }
7414
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007415 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007416 for (int i=0; i<pids.length; i++) {
7417 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7418 if (proc == null) {
7419 continue;
7420 }
7421 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007422 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007423 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007424 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7425 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007426 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007427 proc.killedBackground = true;
7428 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007429 }
7430 }
7431 }
7432 return killed;
7433 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007434
7435 @Override
7436 public boolean killProcessesBelowForeground(String reason) {
7437 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7438 throw new SecurityException("killProcessesBelowForeground() only available to system");
7439 }
7440
7441 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7442 }
7443
7444 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7445 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7446 throw new SecurityException("killProcessesBelowAdj() only available to system");
7447 }
7448
7449 boolean killed = false;
7450 synchronized (mPidsSelfLocked) {
7451 final int size = mPidsSelfLocked.size();
7452 for (int i = 0; i < size; i++) {
7453 final int pid = mPidsSelfLocked.keyAt(i);
7454 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7455 if (proc == null) continue;
7456
7457 final int adj = proc.setAdj;
7458 if (adj > belowAdj && !proc.killedBackground) {
7459 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7460 EventLog.writeEvent(
7461 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7462 killed = true;
7463 proc.killedBackground = true;
7464 Process.killProcessQuiet(pid);
7465 }
7466 }
7467 }
7468 return killed;
7469 }
7470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007471 public final void startRunning(String pkg, String cls, String action,
7472 String data) {
7473 synchronized(this) {
7474 if (mStartRunning) {
7475 return;
7476 }
7477 mStartRunning = true;
7478 mTopComponent = pkg != null && cls != null
7479 ? new ComponentName(pkg, cls) : null;
7480 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7481 mTopData = data;
7482 if (!mSystemReady) {
7483 return;
7484 }
7485 }
7486
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007487 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007488 }
7489
7490 private void retrieveSettings() {
7491 final ContentResolver resolver = mContext.getContentResolver();
7492 String debugApp = Settings.System.getString(
7493 resolver, Settings.System.DEBUG_APP);
7494 boolean waitForDebugger = Settings.System.getInt(
7495 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7496 boolean alwaysFinishActivities = Settings.System.getInt(
7497 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7498
7499 Configuration configuration = new Configuration();
7500 Settings.System.getConfiguration(resolver, configuration);
7501
7502 synchronized (this) {
7503 mDebugApp = mOrigDebugApp = debugApp;
7504 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7505 mAlwaysFinishActivities = alwaysFinishActivities;
7506 // This happens before any activities are started, so we can
7507 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007508 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007509 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007510 }
7511 }
7512
7513 public boolean testIsSystemReady() {
7514 // no need to synchronize(this) just to read & return the value
7515 return mSystemReady;
7516 }
7517
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007518 private static File getCalledPreBootReceiversFile() {
7519 File dataDir = Environment.getDataDirectory();
7520 File systemDir = new File(dataDir, "system");
7521 File fname = new File(systemDir, "called_pre_boots.dat");
7522 return fname;
7523 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007524
7525 static final int LAST_DONE_VERSION = 10000;
7526
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007527 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7528 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7529 File file = getCalledPreBootReceiversFile();
7530 FileInputStream fis = null;
7531 try {
7532 fis = new FileInputStream(file);
7533 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007534 int fvers = dis.readInt();
7535 if (fvers == LAST_DONE_VERSION) {
7536 String vers = dis.readUTF();
7537 String codename = dis.readUTF();
7538 String build = dis.readUTF();
7539 if (android.os.Build.VERSION.RELEASE.equals(vers)
7540 && android.os.Build.VERSION.CODENAME.equals(codename)
7541 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7542 int num = dis.readInt();
7543 while (num > 0) {
7544 num--;
7545 String pkg = dis.readUTF();
7546 String cls = dis.readUTF();
7547 lastDoneReceivers.add(new ComponentName(pkg, cls));
7548 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007549 }
7550 }
7551 } catch (FileNotFoundException e) {
7552 } catch (IOException e) {
7553 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7554 } finally {
7555 if (fis != null) {
7556 try {
7557 fis.close();
7558 } catch (IOException e) {
7559 }
7560 }
7561 }
7562 return lastDoneReceivers;
7563 }
7564
7565 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7566 File file = getCalledPreBootReceiversFile();
7567 FileOutputStream fos = null;
7568 DataOutputStream dos = null;
7569 try {
7570 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7571 fos = new FileOutputStream(file);
7572 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007573 dos.writeInt(LAST_DONE_VERSION);
7574 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007575 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007576 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007577 dos.writeInt(list.size());
7578 for (int i=0; i<list.size(); i++) {
7579 dos.writeUTF(list.get(i).getPackageName());
7580 dos.writeUTF(list.get(i).getClassName());
7581 }
7582 } catch (IOException e) {
7583 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7584 file.delete();
7585 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007586 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007587 if (dos != null) {
7588 try {
7589 dos.close();
7590 } catch (IOException e) {
7591 // TODO Auto-generated catch block
7592 e.printStackTrace();
7593 }
7594 }
7595 }
7596 }
7597
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007598 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007599 synchronized(this) {
7600 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007601 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007602 return;
7603 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007604
7605 // Check to see if there are any update receivers to run.
7606 if (!mDidUpdate) {
7607 if (mWaitingUpdate) {
7608 return;
7609 }
7610 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7611 List<ResolveInfo> ris = null;
7612 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007613 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007614 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007615 } catch (RemoteException e) {
7616 }
7617 if (ris != null) {
7618 for (int i=ris.size()-1; i>=0; i--) {
7619 if ((ris.get(i).activityInfo.applicationInfo.flags
7620 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7621 ris.remove(i);
7622 }
7623 }
7624 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007625
7626 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7627
7628 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007629 for (int i=0; i<ris.size(); i++) {
7630 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007631 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7632 if (lastDoneReceivers.contains(comp)) {
7633 ris.remove(i);
7634 i--;
7635 }
7636 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007637
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007638 for (int i=0; i<ris.size(); i++) {
7639 ActivityInfo ai = ris.get(i).activityInfo;
7640 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7641 doneReceivers.add(comp);
7642 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007643 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007644 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007645 finisher = new IIntentReceiver.Stub() {
7646 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007647 String data, Bundle extras, boolean ordered,
Dianne Hackborn20e80982012-08-31 19:00:44 -07007648 boolean sticky, int sendingUser) {
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007649 // The raw IIntentReceiver interface is called
7650 // with the AM lock held, so redispatch to
7651 // execute our code without the lock.
7652 mHandler.post(new Runnable() {
7653 public void run() {
7654 synchronized (ActivityManagerService.this) {
7655 mDidUpdate = true;
7656 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007657 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007658 showBootMessage(mContext.getText(
7659 R.string.android_upgrading_complete),
7660 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007661 systemReady(goingCallback);
7662 }
7663 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007664 }
7665 };
7666 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007667 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007668 // XXX also need to send this to stopped users(!!!)
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007669 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007670 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007671 UserHandle.USER_ALL);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007672 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007673 mWaitingUpdate = true;
7674 }
7675 }
7676 }
7677 if (mWaitingUpdate) {
7678 return;
7679 }
7680 mDidUpdate = true;
7681 }
7682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007683 mSystemReady = true;
7684 if (!mStartRunning) {
7685 return;
7686 }
7687 }
7688
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007689 ArrayList<ProcessRecord> procsToKill = null;
7690 synchronized(mPidsSelfLocked) {
7691 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7692 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7693 if (!isAllowedWhileBooting(proc.info)){
7694 if (procsToKill == null) {
7695 procsToKill = new ArrayList<ProcessRecord>();
7696 }
7697 procsToKill.add(proc);
7698 }
7699 }
7700 }
7701
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007702 synchronized(this) {
7703 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007704 for (int i=procsToKill.size()-1; i>=0; i--) {
7705 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007706 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007707 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007708 }
7709 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007710
7711 // Now that we have cleaned up any update processes, we
7712 // are ready to start launching real processes and know that
7713 // we won't trample on them any more.
7714 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007715 }
7716
Joe Onorato8a9b2202010-02-26 18:56:32 -08007717 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007718 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007719 SystemClock.uptimeMillis());
7720
7721 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007722 // Make sure we have no pre-ready processes sitting around.
7723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007724 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7725 ResolveInfo ri = mContext.getPackageManager()
7726 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007727 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007728 CharSequence errorMsg = null;
7729 if (ri != null) {
7730 ActivityInfo ai = ri.activityInfo;
7731 ApplicationInfo app = ai.applicationInfo;
7732 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7733 mTopAction = Intent.ACTION_FACTORY_TEST;
7734 mTopData = null;
7735 mTopComponent = new ComponentName(app.packageName,
7736 ai.name);
7737 } else {
7738 errorMsg = mContext.getResources().getText(
7739 com.android.internal.R.string.factorytest_not_system);
7740 }
7741 } else {
7742 errorMsg = mContext.getResources().getText(
7743 com.android.internal.R.string.factorytest_no_action);
7744 }
7745 if (errorMsg != null) {
7746 mTopAction = null;
7747 mTopData = null;
7748 mTopComponent = null;
7749 Message msg = Message.obtain();
7750 msg.what = SHOW_FACTORY_ERROR_MSG;
7751 msg.getData().putCharSequence("msg", errorMsg);
7752 mHandler.sendMessage(msg);
7753 }
7754 }
7755 }
7756
7757 retrieveSettings();
7758
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007759 if (goingCallback != null) goingCallback.run();
7760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007761 synchronized (this) {
7762 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7763 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007764 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007765 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007766 if (apps != null) {
7767 int N = apps.size();
7768 int i;
7769 for (i=0; i<N; i++) {
7770 ApplicationInfo info
7771 = (ApplicationInfo)apps.get(i);
7772 if (info != null &&
7773 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007774 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007775 }
7776 }
7777 }
7778 } catch (RemoteException ex) {
7779 // pm is in same process, this will never happen.
7780 }
7781 }
7782
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007783 // Start up initial activity.
7784 mBooting = true;
7785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007786 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007787 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 Message msg = Message.obtain();
7789 msg.what = SHOW_UID_ERROR_MSG;
7790 mHandler.sendMessage(msg);
7791 }
7792 } catch (RemoteException e) {
7793 }
7794
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007795 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007796 }
7797 }
7798
Dan Egnorb7f03672009-12-09 16:22:32 -08007799 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007800 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007802 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007803 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007804 startAppProblemLocked(app);
7805 app.stopFreezingAllLocked();
7806 return handleAppCrashLocked(app);
7807 }
7808
Dan Egnorb7f03672009-12-09 16:22:32 -08007809 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007810 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007811 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007812 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007813 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7814 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 startAppProblemLocked(app);
7816 app.stopFreezingAllLocked();
7817 }
7818
7819 /**
7820 * Generate a process error record, suitable for attachment to a ProcessRecord.
7821 *
7822 * @param app The ProcessRecord in which the error occurred.
7823 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7824 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007825 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 * @param shortMsg Short message describing the crash.
7827 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007828 * @param stackTrace Full crash stack trace, may be null.
7829 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007830 * @return Returns a fully-formed AppErrorStateInfo record.
7831 */
7832 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007833 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007834 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 report.condition = condition;
7837 report.processName = app.processName;
7838 report.pid = app.pid;
7839 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007840 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007841 report.shortMsg = shortMsg;
7842 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007843 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007844
7845 return report;
7846 }
7847
Dan Egnor42471dd2010-01-07 17:25:22 -08007848 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007849 synchronized (this) {
7850 app.crashing = false;
7851 app.crashingReport = null;
7852 app.notResponding = false;
7853 app.notRespondingReport = null;
7854 if (app.anrDialog == fromDialog) {
7855 app.anrDialog = null;
7856 }
7857 if (app.waitDialog == fromDialog) {
7858 app.waitDialog = null;
7859 }
7860 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007861 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007862 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007863 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7864 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007865 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007866 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007867 }
7868 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007869
Dan Egnorb7f03672009-12-09 16:22:32 -08007870 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007871 if (mHeadless) {
7872 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7873 return false;
7874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007875 long now = SystemClock.uptimeMillis();
7876
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007877 Long crashTime;
7878 if (!app.isolated) {
7879 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7880 } else {
7881 crashTime = null;
7882 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007883 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007885 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007886 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007887 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007888 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007889 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7890 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007891 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007892 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007893 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007894 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007895 }
7896 }
7897 if (!app.persistent) {
7898 // We don't want to start this process again until the user
7899 // explicitly does so... but for persistent process, we really
7900 // need to keep it running. If a persistent process is actually
7901 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007902 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007904 if (!app.isolated) {
7905 // XXX We don't have a way to mark isolated processes
7906 // as bad, since they don't have a peristent identity.
7907 mBadProcesses.put(app.info.processName, app.uid, now);
7908 mProcessCrashTimes.remove(app.info.processName, app.uid);
7909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007910 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007911 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007912 // Don't let services in this process be restarted and potentially
7913 // annoy the user repeatedly. Unless it is persistent, since those
7914 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007915 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007916 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007917 return false;
7918 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007919 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007920 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007921 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007922 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007923 // If the top running activity is from this crashing
7924 // process, then terminate it to avoid getting in a loop.
7925 Slog.w(TAG, " Force finishing activity "
7926 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007927 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007928 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007929 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007930 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007931 // stopped, to avoid a situation where one will get
7932 // re-start our crashing activity once it gets resumed again.
7933 index--;
7934 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007935 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007936 if (r.state == ActivityState.RESUMED
7937 || r.state == ActivityState.PAUSING
7938 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007939 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007940 Slog.w(TAG, " Force finishing activity "
7941 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007942 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007943 Activity.RESULT_CANCELED, null, "crashed");
7944 }
7945 }
7946 }
7947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007948 }
7949
7950 // Bump up the crash count of any services currently running in the proc.
7951 if (app.services.size() != 0) {
7952 // Any services running in the application need to be placed
7953 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007954 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007956 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 sr.crashCount++;
7958 }
7959 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007960
7961 // If the crashing process is what we consider to be the "home process" and it has been
7962 // replaced by a third-party app, clear the package preferred activities from packages
7963 // with a home activity running in the process to prevent a repeatedly crashing app
7964 // from blocking the user to manually clear the list.
7965 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7966 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7967 Iterator it = mHomeProcess.activities.iterator();
7968 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007969 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007970 if (r.isHomeActivity) {
7971 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7972 try {
7973 ActivityThread.getPackageManager()
7974 .clearPackagePreferredActivities(r.packageName);
7975 } catch (RemoteException c) {
7976 // pm is in same process, this will never happen.
7977 }
7978 }
7979 }
7980 }
7981
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007982 if (!app.isolated) {
7983 // XXX Can't keep track of crash times for isolated processes,
7984 // because they don't have a perisistent identity.
7985 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7986 }
7987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007988 return true;
7989 }
7990
7991 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007992 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7993 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007994 skipCurrentReceiverLocked(app);
7995 }
7996
7997 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007998 for (BroadcastQueue queue : mBroadcastQueues) {
7999 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 }
8001 }
8002
Dan Egnor60d87622009-12-16 16:32:58 -08008003 /**
8004 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
8005 * The application process will exit immediately after this call returns.
8006 * @param app object of the crashing app, null for the system server
8007 * @param crashInfo describing the exception
8008 */
8009 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008010 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008011 final String processName = app == null ? "system_server"
8012 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008013
8014 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008015 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008016 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008017 crashInfo.exceptionClassName,
8018 crashInfo.exceptionMessage,
8019 crashInfo.throwFileName,
8020 crashInfo.throwLineNumber);
8021
Jeff Sharkeya353d262011-10-28 11:12:06 -07008022 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008023
8024 crashApplication(r, crashInfo);
8025 }
8026
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008027 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008028 IBinder app,
8029 int violationMask,
8030 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008031 ProcessRecord r = findAppProcess(app, "StrictMode");
8032 if (r == null) {
8033 return;
8034 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008035
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008036 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08008037 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008038 boolean logIt = true;
8039 synchronized (mAlreadyLoggedViolatedStacks) {
8040 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
8041 logIt = false;
8042 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008043 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008044 // the relative pain numbers, without logging all
8045 // the stack traces repeatedly. We'd want to do
8046 // likewise in the client code, which also does
8047 // dup suppression, before the Binder call.
8048 } else {
8049 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
8050 mAlreadyLoggedViolatedStacks.clear();
8051 }
8052 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
8053 }
8054 }
8055 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008056 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008057 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008058 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008059
8060 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
8061 AppErrorResult result = new AppErrorResult();
8062 synchronized (this) {
8063 final long origId = Binder.clearCallingIdentity();
8064
8065 Message msg = Message.obtain();
8066 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
8067 HashMap<String, Object> data = new HashMap<String, Object>();
8068 data.put("result", result);
8069 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07008070 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008071 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008072 msg.obj = data;
8073 mHandler.sendMessage(msg);
8074
8075 Binder.restoreCallingIdentity(origId);
8076 }
8077 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07008078 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07008079 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07008080 }
8081
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008082 // Depending on the policy in effect, there could be a bunch of
8083 // these in quick succession so we try to batch these together to
8084 // minimize disk writes, number of dropbox entries, and maximize
8085 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008086 private void logStrictModeViolationToDropBox(
8087 ProcessRecord process,
8088 StrictMode.ViolationInfo info) {
8089 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008090 return;
8091 }
8092 final boolean isSystemApp = process == null ||
8093 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8094 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008095 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008096 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8097 final DropBoxManager dbox = (DropBoxManager)
8098 mContext.getSystemService(Context.DROPBOX_SERVICE);
8099
8100 // Exit early if the dropbox isn't configured to accept this report type.
8101 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8102
8103 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008104 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008105 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8106 synchronized (sb) {
8107 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008108 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008109 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8110 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008111 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8112 if (info.violationNumThisLoop != 0) {
8113 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8114 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008115 if (info.numAnimationsRunning != 0) {
8116 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8117 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008118 if (info.broadcastIntentAction != null) {
8119 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8120 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008121 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008122 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008123 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008124 if (info.numInstances != -1) {
8125 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8126 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008127 if (info.tags != null) {
8128 for (String tag : info.tags) {
8129 sb.append("Span-Tag: ").append(tag).append("\n");
8130 }
8131 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008132 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008133 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8134 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008135 }
8136 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008137
8138 // Only buffer up to ~64k. Various logging bits truncate
8139 // things at 128k.
8140 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008141 }
8142
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008143 // Flush immediately if the buffer's grown too large, or this
8144 // is a non-system app. Non-system apps are isolated with a
8145 // different tag & policy and not batched.
8146 //
8147 // Batching is useful during internal testing with
8148 // StrictMode settings turned up high. Without batching,
8149 // thousands of separate files could be created on boot.
8150 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008151 new Thread("Error dump: " + dropboxTag) {
8152 @Override
8153 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008154 String report;
8155 synchronized (sb) {
8156 report = sb.toString();
8157 sb.delete(0, sb.length());
8158 sb.trimToSize();
8159 }
8160 if (report.length() != 0) {
8161 dbox.addText(dropboxTag, report);
8162 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008163 }
8164 }.start();
8165 return;
8166 }
8167
8168 // System app batching:
8169 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008170 // An existing dropbox-writing thread is outstanding, so
8171 // we don't need to start it up. The existing thread will
8172 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008173 return;
8174 }
8175
8176 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8177 // (After this point, we shouldn't access AMS internal data structures.)
8178 new Thread("Error dump: " + dropboxTag) {
8179 @Override
8180 public void run() {
8181 // 5 second sleep to let stacks arrive and be batched together
8182 try {
8183 Thread.sleep(5000); // 5 seconds
8184 } catch (InterruptedException e) {}
8185
8186 String errorReport;
8187 synchronized (mStrictModeBuffer) {
8188 errorReport = mStrictModeBuffer.toString();
8189 if (errorReport.length() == 0) {
8190 return;
8191 }
8192 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8193 mStrictModeBuffer.trimToSize();
8194 }
8195 dbox.addText(dropboxTag, errorReport);
8196 }
8197 }.start();
8198 }
8199
Dan Egnor60d87622009-12-16 16:32:58 -08008200 /**
8201 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8202 * @param app object of the crashing app, null for the system server
8203 * @param tag reported by the caller
8204 * @param crashInfo describing the context of the error
8205 * @return true if the process should exit immediately (WTF is fatal)
8206 */
8207 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008208 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008209 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008210 final String processName = app == null ? "system_server"
8211 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008212
8213 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008214 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008215 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008216 tag, crashInfo.exceptionMessage);
8217
Jeff Sharkeya353d262011-10-28 11:12:06 -07008218 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008219
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008220 if (r != null && r.pid != Process.myPid() &&
8221 Settings.Secure.getInt(mContext.getContentResolver(),
8222 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008223 crashApplication(r, crashInfo);
8224 return true;
8225 } else {
8226 return false;
8227 }
8228 }
8229
8230 /**
8231 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8232 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8233 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008234 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008235 if (app == null) {
8236 return null;
8237 }
8238
8239 synchronized (this) {
8240 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8241 final int NA = apps.size();
8242 for (int ia=0; ia<NA; ia++) {
8243 ProcessRecord p = apps.valueAt(ia);
8244 if (p.thread != null && p.thread.asBinder() == app) {
8245 return p;
8246 }
8247 }
8248 }
8249
Dianne Hackborncb44d962011-03-10 17:02:27 -08008250 Slog.w(TAG, "Can't find mystery application for " + reason
8251 + " from pid=" + Binder.getCallingPid()
8252 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008253 return null;
8254 }
8255 }
8256
8257 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008258 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8259 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008260 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008261 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8262 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008263 // Watchdog thread ends up invoking this function (with
8264 // a null ProcessRecord) to add the stack file to dropbox.
8265 // Do not acquire a lock on this (am) in such cases, as it
8266 // could cause a potential deadlock, if and when watchdog
8267 // is invoked due to unavailability of lock on am and it
8268 // would prevent watchdog from killing system_server.
8269 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008270 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008271 return;
8272 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008273 // Note: ProcessRecord 'process' is guarded by the service
8274 // instance. (notably process.pkgList, which could otherwise change
8275 // concurrently during execution of this method)
8276 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008277 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008278 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008279 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008280 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8281 for (String pkg : process.pkgList) {
8282 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008283 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008284 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008285 if (pi != null) {
8286 sb.append(" v").append(pi.versionCode);
8287 if (pi.versionName != null) {
8288 sb.append(" (").append(pi.versionName).append(")");
8289 }
8290 }
8291 } catch (RemoteException e) {
8292 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008293 }
Dan Egnora455d192010-03-12 08:52:28 -08008294 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008295 }
Dan Egnora455d192010-03-12 08:52:28 -08008296 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008297 }
8298
8299 private static String processClass(ProcessRecord process) {
8300 if (process == null || process.pid == MY_PID) {
8301 return "system_server";
8302 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8303 return "system_app";
8304 } else {
8305 return "data_app";
8306 }
8307 }
8308
8309 /**
8310 * Write a description of an error (crash, WTF, ANR) to the drop box.
8311 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8312 * @param process which caused the error, null means the system server
8313 * @param activity which triggered the error, null if unknown
8314 * @param parent activity related to the error, null if unknown
8315 * @param subject line related to the error, null if absent
8316 * @param report in long form describing the error, null if absent
8317 * @param logFile to include in the report, null if none
8318 * @param crashInfo giving an application stack trace, null if absent
8319 */
8320 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008321 ProcessRecord process, String processName, ActivityRecord activity,
8322 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008323 final String report, final File logFile,
8324 final ApplicationErrorReport.CrashInfo crashInfo) {
8325 // NOTE -- this must never acquire the ActivityManagerService lock,
8326 // otherwise the watchdog may be prevented from resetting the system.
8327
8328 final String dropboxTag = processClass(process) + "_" + eventType;
8329 final DropBoxManager dbox = (DropBoxManager)
8330 mContext.getSystemService(Context.DROPBOX_SERVICE);
8331
8332 // Exit early if the dropbox isn't configured to accept this report type.
8333 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8334
8335 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008336 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008337 if (activity != null) {
8338 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8339 }
8340 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8341 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8342 }
8343 if (parent != null && parent != activity) {
8344 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8345 }
8346 if (subject != null) {
8347 sb.append("Subject: ").append(subject).append("\n");
8348 }
8349 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008350 if (Debug.isDebuggerConnected()) {
8351 sb.append("Debugger: Connected\n");
8352 }
Dan Egnora455d192010-03-12 08:52:28 -08008353 sb.append("\n");
8354
8355 // Do the rest in a worker thread to avoid blocking the caller on I/O
8356 // (After this point, we shouldn't access AMS internal data structures.)
8357 Thread worker = new Thread("Error dump: " + dropboxTag) {
8358 @Override
8359 public void run() {
8360 if (report != null) {
8361 sb.append(report);
8362 }
8363 if (logFile != null) {
8364 try {
8365 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8366 } catch (IOException e) {
8367 Slog.e(TAG, "Error reading " + logFile, e);
8368 }
8369 }
8370 if (crashInfo != null && crashInfo.stackTrace != null) {
8371 sb.append(crashInfo.stackTrace);
8372 }
8373
8374 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8375 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8376 if (lines > 0) {
8377 sb.append("\n");
8378
8379 // Merge several logcat streams, and take the last N lines
8380 InputStreamReader input = null;
8381 try {
8382 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8383 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8384 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8385
8386 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8387 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8388 input = new InputStreamReader(logcat.getInputStream());
8389
8390 int num;
8391 char[] buf = new char[8192];
8392 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8393 } catch (IOException e) {
8394 Slog.e(TAG, "Error running logcat", e);
8395 } finally {
8396 if (input != null) try { input.close(); } catch (IOException e) {}
8397 }
8398 }
8399
8400 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008401 }
Dan Egnora455d192010-03-12 08:52:28 -08008402 };
8403
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008404 if (process == null) {
8405 // If process is null, we are being called from some internal code
8406 // and may be about to die -- run this synchronously.
8407 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008408 } else {
8409 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008410 }
8411 }
8412
8413 /**
8414 * Bring up the "unexpected error" dialog box for a crashing app.
8415 * Deal with edge cases (intercepts from instrumented applications,
8416 * ActivityController, error intent receivers, that sort of thing).
8417 * @param r the application crashing
8418 * @param crashInfo describing the failure
8419 */
8420 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008421 long timeMillis = System.currentTimeMillis();
8422 String shortMsg = crashInfo.exceptionClassName;
8423 String longMsg = crashInfo.exceptionMessage;
8424 String stackTrace = crashInfo.stackTrace;
8425 if (shortMsg != null && longMsg != null) {
8426 longMsg = shortMsg + ": " + longMsg;
8427 } else if (shortMsg != null) {
8428 longMsg = shortMsg;
8429 }
8430
Dan Egnor60d87622009-12-16 16:32:58 -08008431 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008432 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008433 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008434 try {
8435 String name = r != null ? r.processName : null;
8436 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008437 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008438 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008439 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008440 + " at watcher's request");
8441 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008442 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008443 }
8444 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008445 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008446 }
8447 }
8448
8449 final long origId = Binder.clearCallingIdentity();
8450
8451 // If this process is running instrumentation, finish it.
8452 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008453 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008454 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008455 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8456 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008457 Bundle info = new Bundle();
8458 info.putString("shortMsg", shortMsg);
8459 info.putString("longMsg", longMsg);
8460 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8461 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008462 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008463 }
8464
Dan Egnor60d87622009-12-16 16:32:58 -08008465 // If we can't identify the process or it's already exceeded its crash quota,
8466 // quit right away without showing a crash dialog.
8467 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008468 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008469 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008470 }
8471
8472 Message msg = Message.obtain();
8473 msg.what = SHOW_ERROR_MSG;
8474 HashMap data = new HashMap();
8475 data.put("result", result);
8476 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008477 msg.obj = data;
8478 mHandler.sendMessage(msg);
8479
8480 Binder.restoreCallingIdentity(origId);
8481 }
8482
8483 int res = result.get();
8484
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008485 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008486 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008487 if (r != null && !r.isolated) {
8488 // XXX Can't keep track of crash time for isolated processes,
8489 // since they don't have a persistent identity.
8490 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008491 SystemClock.uptimeMillis());
8492 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008493 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008494 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008495 }
8496 }
8497
8498 if (appErrorIntent != null) {
8499 try {
8500 mContext.startActivity(appErrorIntent);
8501 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008502 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008505 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008506
8507 Intent createAppErrorIntentLocked(ProcessRecord r,
8508 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8509 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008510 if (report == null) {
8511 return null;
8512 }
8513 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8514 result.setComponent(r.errorReportReceiver);
8515 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8516 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8517 return result;
8518 }
8519
Dan Egnorb7f03672009-12-09 16:22:32 -08008520 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8521 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008522 if (r.errorReportReceiver == null) {
8523 return null;
8524 }
8525
8526 if (!r.crashing && !r.notResponding) {
8527 return null;
8528 }
8529
Dan Egnorb7f03672009-12-09 16:22:32 -08008530 ApplicationErrorReport report = new ApplicationErrorReport();
8531 report.packageName = r.info.packageName;
8532 report.installerPackageName = r.errorReportReceiver.getPackageName();
8533 report.processName = r.processName;
8534 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008535 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008536
Dan Egnorb7f03672009-12-09 16:22:32 -08008537 if (r.crashing) {
8538 report.type = ApplicationErrorReport.TYPE_CRASH;
8539 report.crashInfo = crashInfo;
8540 } else if (r.notResponding) {
8541 report.type = ApplicationErrorReport.TYPE_ANR;
8542 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008543
Dan Egnorb7f03672009-12-09 16:22:32 -08008544 report.anrInfo.activity = r.notRespondingReport.tag;
8545 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8546 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008547 }
8548
Dan Egnorb7f03672009-12-09 16:22:32 -08008549 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008550 }
8551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008552 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008553 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 // assume our apps are happy - lazy create the list
8555 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8556
Dianne Hackborn0c380492012-08-20 17:23:30 -07008557 final boolean allUsers = ActivityManager.checkUidPermission(
8558 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8559 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8560 int userId = UserHandle.getUserId(Binder.getCallingUid());
8561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008562 synchronized (this) {
8563
8564 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008565 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8566 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008567 if (!allUsers && app.userId != userId) {
8568 continue;
8569 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008570 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8571 // This one's in trouble, so we'll generate a report for it
8572 // crashes are higher priority (in case there's a crash *and* an anr)
8573 ActivityManager.ProcessErrorStateInfo report = null;
8574 if (app.crashing) {
8575 report = app.crashingReport;
8576 } else if (app.notResponding) {
8577 report = app.notRespondingReport;
8578 }
8579
8580 if (report != null) {
8581 if (errList == null) {
8582 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8583 }
8584 errList.add(report);
8585 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008586 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 " crashing = " + app.crashing +
8588 " notResponding = " + app.notResponding);
8589 }
8590 }
8591 }
8592 }
8593
8594 return errList;
8595 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008596
8597 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008598 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008599 if (currApp != null) {
8600 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8601 }
8602 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008603 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8604 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008605 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8606 if (currApp != null) {
8607 currApp.lru = 0;
8608 }
8609 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008610 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008611 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8612 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8613 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8614 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8615 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8616 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8617 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8618 } else {
8619 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8620 }
8621 }
8622
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008623 private void fillInProcMemInfo(ProcessRecord app,
8624 ActivityManager.RunningAppProcessInfo outInfo) {
8625 outInfo.pid = app.pid;
8626 outInfo.uid = app.info.uid;
8627 if (mHeavyWeightProcess == app) {
8628 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8629 }
8630 if (app.persistent) {
8631 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8632 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008633 if (app.hasActivities) {
8634 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8635 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008636 outInfo.lastTrimLevel = app.trimMemoryLevel;
8637 int adj = app.curAdj;
8638 outInfo.importance = oomAdjToImportance(adj, outInfo);
8639 outInfo.importanceReasonCode = app.adjTypeCode;
8640 }
8641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008642 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008643 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644 // Lazy instantiation of list
8645 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008646 final boolean allUsers = ActivityManager.checkUidPermission(
8647 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8648 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8649 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008650 synchronized (this) {
8651 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008652 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8653 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008654 if (!allUsers && app.userId != userId) {
8655 continue;
8656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008657 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8658 // Generate process state info for running application
8659 ActivityManager.RunningAppProcessInfo currApp =
8660 new ActivityManager.RunningAppProcessInfo(app.processName,
8661 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008662 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008663 if (app.adjSource instanceof ProcessRecord) {
8664 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008665 currApp.importanceReasonImportance = oomAdjToImportance(
8666 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008667 } else if (app.adjSource instanceof ActivityRecord) {
8668 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008669 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8670 }
8671 if (app.adjTarget instanceof ComponentName) {
8672 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8673 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008674 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008675 // + " lru=" + currApp.lru);
8676 if (runList == null) {
8677 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8678 }
8679 runList.add(currApp);
8680 }
8681 }
8682 }
8683 return runList;
8684 }
8685
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008686 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008687 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008688 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8689 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8690 if (runningApps != null && runningApps.size() > 0) {
8691 Set<String> extList = new HashSet<String>();
8692 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8693 if (app.pkgList != null) {
8694 for (String pkg : app.pkgList) {
8695 extList.add(pkg);
8696 }
8697 }
8698 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008699 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008700 for (String pkg : extList) {
8701 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008702 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008703 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8704 retList.add(info);
8705 }
8706 } catch (RemoteException e) {
8707 }
8708 }
8709 }
8710 return retList;
8711 }
8712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008713 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008714 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8715 enforceNotIsolatedCaller("getMyMemoryState");
8716 synchronized (this) {
8717 ProcessRecord proc;
8718 synchronized (mPidsSelfLocked) {
8719 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8720 }
8721 fillInProcMemInfo(proc, outInfo);
8722 }
8723 }
8724
8725 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008726 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008727 if (checkCallingPermission(android.Manifest.permission.DUMP)
8728 != PackageManager.PERMISSION_GRANTED) {
8729 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8730 + Binder.getCallingPid()
8731 + ", uid=" + Binder.getCallingUid()
8732 + " without permission "
8733 + android.Manifest.permission.DUMP);
8734 return;
8735 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008736
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008737 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008738 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008739 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008740
8741 int opti = 0;
8742 while (opti < args.length) {
8743 String opt = args[opti];
8744 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8745 break;
8746 }
8747 opti++;
8748 if ("-a".equals(opt)) {
8749 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008750 } else if ("-c".equals(opt)) {
8751 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008752 } else if ("-h".equals(opt)) {
8753 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008754 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008755 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008756 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008757 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8758 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8759 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008760 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008761 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008762 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008763 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008764 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008765 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008766 pw.println(" all: dump all activities");
8767 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008768 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008769 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8770 pw.println(" a partial substring in a component name, a");
8771 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008772 pw.println(" -a: include all available server state.");
8773 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008775 } else {
8776 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008777 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008778 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008779
8780 long origId = Binder.clearCallingIdentity();
8781 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008782 // Is the caller requesting to dump a particular piece of data?
8783 if (opti < args.length) {
8784 String cmd = args[opti];
8785 opti++;
8786 if ("activities".equals(cmd) || "a".equals(cmd)) {
8787 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008788 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008789 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008790 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008791 String[] newArgs;
8792 String name;
8793 if (opti >= args.length) {
8794 name = null;
8795 newArgs = EMPTY_STRING_ARRAY;
8796 } else {
8797 name = args[opti];
8798 opti++;
8799 newArgs = new String[args.length - opti];
8800 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8801 args.length - opti);
8802 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008803 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008804 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008805 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008806 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008807 String[] newArgs;
8808 String name;
8809 if (opti >= args.length) {
8810 name = null;
8811 newArgs = EMPTY_STRING_ARRAY;
8812 } else {
8813 name = args[opti];
8814 opti++;
8815 newArgs = new String[args.length - opti];
8816 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8817 args.length - opti);
8818 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008819 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008820 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008821 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008822 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008823 String[] newArgs;
8824 String name;
8825 if (opti >= args.length) {
8826 name = null;
8827 newArgs = EMPTY_STRING_ARRAY;
8828 } else {
8829 name = args[opti];
8830 opti++;
8831 newArgs = new String[args.length - opti];
8832 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8833 args.length - opti);
8834 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008835 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008836 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008837 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008838 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8839 synchronized (this) {
8840 dumpOomLocked(fd, pw, args, opti, true);
8841 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008842 } else if ("provider".equals(cmd)) {
8843 String[] newArgs;
8844 String name;
8845 if (opti >= args.length) {
8846 name = null;
8847 newArgs = EMPTY_STRING_ARRAY;
8848 } else {
8849 name = args[opti];
8850 opti++;
8851 newArgs = new String[args.length - opti];
8852 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8853 }
8854 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8855 pw.println("No providers match: " + name);
8856 pw.println("Use -h for help.");
8857 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008858 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8859 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008860 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008861 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008862 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008863 String[] newArgs;
8864 String name;
8865 if (opti >= args.length) {
8866 name = null;
8867 newArgs = EMPTY_STRING_ARRAY;
8868 } else {
8869 name = args[opti];
8870 opti++;
8871 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008872 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8873 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008874 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008875 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008876 pw.println("No services match: " + name);
8877 pw.println("Use -h for help.");
8878 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008879 } else if ("package".equals(cmd)) {
8880 String[] newArgs;
8881 if (opti >= args.length) {
8882 pw.println("package: no package name specified");
8883 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008884 } else {
8885 dumpPackage = args[opti];
8886 opti++;
8887 newArgs = new String[args.length - opti];
8888 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8889 args.length - opti);
8890 args = newArgs;
8891 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008892 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008893 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008894 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8895 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008896 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008897 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008898 } else {
8899 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008900 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8901 pw.println("Bad activity command, or no activities match: " + cmd);
8902 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008903 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008904 }
8905 if (!more) {
8906 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008907 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008908 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008909 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008910
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008911 // No piece of data specified, dump everything.
8912 synchronized (this) {
8913 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008914 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008915 if (needSep) {
8916 pw.println(" ");
8917 }
8918 if (dumpAll) {
8919 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008920 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008921 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008922 if (needSep) {
8923 pw.println(" ");
8924 }
8925 if (dumpAll) {
8926 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008927 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008928 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008929 if (needSep) {
8930 pw.println(" ");
8931 }
8932 if (dumpAll) {
8933 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008934 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008935 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008936 if (needSep) {
8937 pw.println(" ");
8938 }
8939 if (dumpAll) {
8940 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008941 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008942 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008943 if (needSep) {
8944 pw.println(" ");
8945 }
8946 if (dumpAll) {
8947 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008948 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008949 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008950 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008951 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008952 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008953
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008954 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008955 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008956 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8957 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008958 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8959 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008960 pw.println(" ");
8961 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008962 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8963 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008964 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008966 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008967 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008968 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008969 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008970 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008971 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008972 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008973 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008974 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008975 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008976 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8977 pw.println(" ");
8978 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008979 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008980 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008981 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008982 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008983 pw.println(" ");
8984 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008985 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008986 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008987 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008988
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008989 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008990 if (mMainStack.mPausingActivity != null) {
8991 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008992 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008993 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008994 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008995 if (dumpAll) {
8996 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8997 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008998 pw.println(" mDismissKeyguardOnNextActivity: "
8999 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009002 if (mRecentTasks.size() > 0) {
9003 pw.println();
9004 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009005
9006 final int N = mRecentTasks.size();
9007 for (int i=0; i<N; i++) {
9008 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009009 if (dumpPackage != null) {
9010 if (tr.realActivity == null ||
9011 !dumpPackage.equals(tr.realActivity)) {
9012 continue;
9013 }
9014 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009015 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
9016 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009017 if (dumpAll) {
9018 mRecentTasks.get(i).dump(pw, " ");
9019 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009020 }
9021 }
9022
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009023 if (dumpAll) {
9024 pw.println(" ");
9025 pw.println(" mCurTask: " + mCurTask);
9026 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009027
9028 return true;
9029 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009030
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009031 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009032 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009033 boolean needSep = false;
9034 int numPers = 0;
9035
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009036 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
9037
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009038 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009039 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
9040 final int NA = procs.size();
9041 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009042 ProcessRecord r = procs.valueAt(ia);
9043 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9044 continue;
9045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009046 if (!needSep) {
9047 pw.println(" All known processes:");
9048 needSep = true;
9049 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009050 pw.print(r.persistent ? " *PERS*" : " *APP*");
9051 pw.print(" UID "); pw.print(procs.keyAt(ia));
9052 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009053 r.dump(pw, " ");
9054 if (r.persistent) {
9055 numPers++;
9056 }
9057 }
9058 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009059 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08009060
9061 if (mIsolatedProcesses.size() > 0) {
9062 if (needSep) pw.println(" ");
9063 needSep = true;
9064 pw.println(" Isolated process list (sorted by uid):");
9065 for (int i=0; i<mIsolatedProcesses.size(); i++) {
9066 ProcessRecord r = mIsolatedProcesses.valueAt(i);
9067 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9068 continue;
9069 }
9070 pw.println(String.format("%sIsolated #%2d: %s",
9071 " ", i, r.toString()));
9072 }
9073 }
9074
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009075 if (mLruProcesses.size() > 0) {
9076 if (needSep) pw.println(" ");
9077 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07009078 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009079 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009080 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009081 needSep = true;
9082 }
9083
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009084 if (dumpAll) {
9085 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009086 boolean printed = false;
9087 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9088 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9089 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9090 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009091 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009092 if (!printed) {
9093 if (needSep) pw.println(" ");
9094 needSep = true;
9095 pw.println(" PID mappings:");
9096 printed = true;
9097 }
9098 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9099 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009100 }
9101 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009102 }
9103
9104 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009105 synchronized (mPidsSelfLocked) {
9106 boolean printed = false;
9107 for (int i=0; i<mForegroundProcesses.size(); i++) {
9108 ProcessRecord r = mPidsSelfLocked.get(
9109 mForegroundProcesses.valueAt(i).pid);
9110 if (dumpPackage != null && (r == null
9111 || !dumpPackage.equals(r.info.packageName))) {
9112 continue;
9113 }
9114 if (!printed) {
9115 if (needSep) pw.println(" ");
9116 needSep = true;
9117 pw.println(" Foreground Processes:");
9118 printed = true;
9119 }
9120 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9121 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009123 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009124 }
9125
9126 if (mPersistentStartingProcesses.size() > 0) {
9127 if (needSep) pw.println(" ");
9128 needSep = true;
9129 pw.println(" Persisent processes that are starting:");
9130 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009131 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009133
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009134 if (mRemovedProcesses.size() > 0) {
9135 if (needSep) pw.println(" ");
9136 needSep = true;
9137 pw.println(" Processes that are being removed:");
9138 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009139 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009140 }
9141
9142 if (mProcessesOnHold.size() > 0) {
9143 if (needSep) pw.println(" ");
9144 needSep = true;
9145 pw.println(" Processes that are on old until the system is ready:");
9146 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009147 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009150 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009151
9152 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009153 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009154 long now = SystemClock.uptimeMillis();
9155 for (Map.Entry<String, SparseArray<Long>> procs
9156 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009157 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009158 SparseArray<Long> uids = procs.getValue();
9159 final int N = uids.size();
9160 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009161 int puid = uids.keyAt(i);
9162 ProcessRecord r = mProcessNames.get(pname, puid);
9163 if (dumpPackage != null && (r == null
9164 || !dumpPackage.equals(r.info.packageName))) {
9165 continue;
9166 }
9167 if (!printed) {
9168 if (needSep) pw.println(" ");
9169 needSep = true;
9170 pw.println(" Time since processes crashed:");
9171 printed = true;
9172 }
9173 pw.print(" Process "); pw.print(pname);
9174 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009175 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009176 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9177 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009178 }
9179 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009182 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009183 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009184 for (Map.Entry<String, SparseArray<Long>> procs
9185 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009186 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009187 SparseArray<Long> uids = procs.getValue();
9188 final int N = uids.size();
9189 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009190 int puid = uids.keyAt(i);
9191 ProcessRecord r = mProcessNames.get(pname, puid);
9192 if (dumpPackage != null && (r == null
9193 || !dumpPackage.equals(r.info.packageName))) {
9194 continue;
9195 }
9196 if (!printed) {
9197 if (needSep) pw.println(" ");
9198 needSep = true;
9199 pw.println(" Bad processes:");
9200 }
9201 pw.print(" Bad process "); pw.print(pname);
9202 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009203 pw.print(": crashed at time ");
9204 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009205 }
9206 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009208
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009209 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009210 pw.println(" mStartedUsers:");
9211 for (int i=0; i<mStartedUsers.size(); i++) {
9212 UserStartedState uss = mStartedUsers.valueAt(i);
9213 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009214 pw.print(": "); uss.dump("", pw);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009215 }
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -07009216 pw.print(" mUserLru: [");
9217 for (int i=0; i<mUserLru.size(); i++) {
9218 if (i > 0) pw.print(", ");
9219 pw.print(mUserLru.get(i));
9220 }
9221 pw.println("]");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009222 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009223 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009224 if (dumpAll) {
9225 StringBuilder sb = new StringBuilder(128);
9226 sb.append(" mPreviousProcessVisibleTime: ");
9227 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9228 pw.println(sb);
9229 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009230 if (mHeavyWeightProcess != null) {
9231 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9232 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009233 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009234 if (dumpAll) {
9235 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009236 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009237 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009238 for (Map.Entry<String, Integer> entry
9239 : mCompatModePackages.getPackages().entrySet()) {
9240 String pkg = entry.getKey();
9241 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009242 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9243 continue;
9244 }
9245 if (!printed) {
9246 pw.println(" mScreenCompatPackages:");
9247 printed = true;
9248 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009249 pw.print(" "); pw.print(pkg); pw.print(": ");
9250 pw.print(mode); pw.println();
9251 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009252 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009253 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009254 if (mSleeping || mWentToSleep || mLockScreenShown) {
9255 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9256 + " mLockScreenShown " + mLockScreenShown);
9257 }
9258 if (mShuttingDown) {
9259 pw.println(" mShuttingDown=" + mShuttingDown);
9260 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009261 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9262 || mOrigWaitForDebugger) {
9263 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9264 + " mDebugTransient=" + mDebugTransient
9265 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9266 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009267 if (mOpenGlTraceApp != null) {
9268 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9269 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009270 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9271 || mProfileFd != null) {
9272 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9273 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9274 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9275 + mAutoStopProfiler);
9276 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009277 if (mAlwaysFinishActivities || mController != null) {
9278 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9279 + " mController=" + mController);
9280 }
9281 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009282 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009283 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009284 + " mProcessesReady=" + mProcessesReady
9285 + " mSystemReady=" + mSystemReady);
9286 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009287 + " mBooted=" + mBooted
9288 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009289 pw.print(" mLastPowerCheckRealtime=");
9290 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9291 pw.println("");
9292 pw.print(" mLastPowerCheckUptime=");
9293 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9294 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009295 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9296 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009297 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009298 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9299 + " mNumHiddenProcs=" + mNumHiddenProcs
9300 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009301 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009302 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009303
9304 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009305 }
9306
Dianne Hackborn287952c2010-09-22 22:34:31 -07009307 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009308 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009309 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009310 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009311 long now = SystemClock.uptimeMillis();
9312 for (int i=0; i<mProcessesToGc.size(); i++) {
9313 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009314 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9315 continue;
9316 }
9317 if (!printed) {
9318 if (needSep) pw.println(" ");
9319 needSep = true;
9320 pw.println(" Processes that are waiting to GC:");
9321 printed = true;
9322 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009323 pw.print(" Process "); pw.println(proc);
9324 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9325 pw.print(", last gced=");
9326 pw.print(now-proc.lastRequestedGc);
9327 pw.print(" ms ago, last lowMem=");
9328 pw.print(now-proc.lastLowMemory);
9329 pw.println(" ms ago");
9330
9331 }
9332 }
9333 return needSep;
9334 }
9335
9336 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9337 int opti, boolean dumpAll) {
9338 boolean needSep = false;
9339
9340 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009341 if (needSep) pw.println(" ");
9342 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009343 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009344 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009345 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009346 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9347 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9348 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9349 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9350 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009351 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009352 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009353 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009354 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009355 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009356 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009357
9358 if (needSep) pw.println(" ");
9359 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009360 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009361 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009362 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009363 needSep = true;
9364 }
9365
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009366 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009367
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009368 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009369 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009370 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009371 if (mHeavyWeightProcess != null) {
9372 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9373 }
9374
9375 return true;
9376 }
9377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009378 /**
9379 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009380 * - no provider specified: dump all the providers
9381 * - a flattened component name that matched an existing provider was specified as the
9382 * first arg: dump that one provider
9383 * - the first arg isn't the flattened component name of an existing provider:
9384 * dump all providers whose component contains the first arg as a substring
9385 */
9386 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9387 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009388 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009389 }
9390
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009391 static class ItemMatcher {
9392 ArrayList<ComponentName> components;
9393 ArrayList<String> strings;
9394 ArrayList<Integer> objects;
9395 boolean all;
9396
9397 ItemMatcher() {
9398 all = true;
9399 }
9400
9401 void build(String name) {
9402 ComponentName componentName = ComponentName.unflattenFromString(name);
9403 if (componentName != null) {
9404 if (components == null) {
9405 components = new ArrayList<ComponentName>();
9406 }
9407 components.add(componentName);
9408 all = false;
9409 } else {
9410 int objectId = 0;
9411 // Not a '/' separated full component name; maybe an object ID?
9412 try {
9413 objectId = Integer.parseInt(name, 16);
9414 if (objects == null) {
9415 objects = new ArrayList<Integer>();
9416 }
9417 objects.add(objectId);
9418 all = false;
9419 } catch (RuntimeException e) {
9420 // Not an integer; just do string match.
9421 if (strings == null) {
9422 strings = new ArrayList<String>();
9423 }
9424 strings.add(name);
9425 all = false;
9426 }
9427 }
9428 }
9429
9430 int build(String[] args, int opti) {
9431 for (; opti<args.length; opti++) {
9432 String name = args[opti];
9433 if ("--".equals(name)) {
9434 return opti+1;
9435 }
9436 build(name);
9437 }
9438 return opti;
9439 }
9440
9441 boolean match(Object object, ComponentName comp) {
9442 if (all) {
9443 return true;
9444 }
9445 if (components != null) {
9446 for (int i=0; i<components.size(); i++) {
9447 if (components.get(i).equals(comp)) {
9448 return true;
9449 }
9450 }
9451 }
9452 if (objects != null) {
9453 for (int i=0; i<objects.size(); i++) {
9454 if (System.identityHashCode(object) == objects.get(i)) {
9455 return true;
9456 }
9457 }
9458 }
9459 if (strings != null) {
9460 String flat = comp.flattenToString();
9461 for (int i=0; i<strings.size(); i++) {
9462 if (flat.contains(strings.get(i))) {
9463 return true;
9464 }
9465 }
9466 }
9467 return false;
9468 }
9469 }
9470
Dianne Hackborn625ac272010-09-17 18:29:22 -07009471 /**
9472 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009473 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009474 * - the cmd arg isn't the flattened component name of an existing activity:
9475 * dump all activity whose component contains the cmd as a substring
9476 * - A hex number of the ActivityRecord object instance.
9477 */
9478 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9479 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009480 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009481
9482 if ("all".equals(name)) {
9483 synchronized (this) {
9484 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009485 activities.add(r1);
9486 }
9487 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009488 } else if ("top".equals(name)) {
9489 synchronized (this) {
9490 final int N = mMainStack.mHistory.size();
9491 if (N > 0) {
9492 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9493 }
9494 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009495 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009496 ItemMatcher matcher = new ItemMatcher();
9497 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009498
9499 synchronized (this) {
9500 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009501 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009502 activities.add(r1);
9503 }
9504 }
9505 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009506 }
9507
9508 if (activities.size() <= 0) {
9509 return false;
9510 }
9511
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009512 String[] newArgs = new String[args.length - opti];
9513 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9514
Dianne Hackborn30d71892010-12-11 10:37:55 -08009515 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009516 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009517 for (int i=activities.size()-1; i>=0; i--) {
9518 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009519 if (needSep) {
9520 pw.println();
9521 }
9522 needSep = true;
9523 synchronized (this) {
9524 if (lastTask != r.task) {
9525 lastTask = r.task;
9526 pw.print("TASK "); pw.print(lastTask.affinity);
9527 pw.print(" id="); pw.println(lastTask.taskId);
9528 if (dumpAll) {
9529 lastTask.dump(pw, " ");
9530 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009531 }
9532 }
9533 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009534 }
9535 return true;
9536 }
9537
9538 /**
9539 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9540 * there is a thread associated with the activity.
9541 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009542 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009543 final ActivityRecord r, String[] args, boolean dumpAll) {
9544 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009545 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009546 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9547 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9548 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009549 if (r.app != null) pw.println(r.app.pid);
9550 else pw.println("(not running)");
9551 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009552 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009553 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009554 }
9555 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009556 // flush anything that is already in the PrintWriter since the thread is going
9557 // to write to the file descriptor directly
9558 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009559 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009560 TransferPipe tp = new TransferPipe();
9561 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009562 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9563 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009564 tp.go(fd);
9565 } finally {
9566 tp.kill();
9567 }
9568 } catch (IOException e) {
9569 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009570 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009571 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009572 }
9573 }
9574 }
9575
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009576 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009577 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009578 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009579 boolean onlyHistory = false;
9580
9581 if ("history".equals(dumpPackage)) {
9582 onlyHistory = true;
9583 dumpPackage = null;
9584 }
9585
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009586 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009587 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009588 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009589 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009590 Iterator it = mRegisteredReceivers.values().iterator();
9591 while (it.hasNext()) {
9592 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009593 if (dumpPackage != null && (r.app == null ||
9594 !dumpPackage.equals(r.app.info.packageName))) {
9595 continue;
9596 }
9597 if (!printed) {
9598 pw.println(" Registered Receivers:");
9599 needSep = true;
9600 printed = true;
9601 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009602 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009603 r.dump(pw, " ");
9604 }
9605 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009606
9607 if (mReceiverResolver.dump(pw, needSep ?
9608 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9609 " ", dumpPackage, false)) {
9610 needSep = true;
9611 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009612 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009613
9614 for (BroadcastQueue q : mBroadcastQueues) {
9615 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009617
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009618 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009619
Dianne Hackborn786b4402012-08-27 15:14:02 -07009620 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009621 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9622 if (needSep) {
9623 pw.println();
9624 }
9625 needSep = true;
9626 pw.print(" Sticky broadcasts for user ");
9627 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9628 StringBuilder sb = new StringBuilder(128);
9629 for (Map.Entry<String, ArrayList<Intent>> ent
9630 : mStickyBroadcasts.valueAt(user).entrySet()) {
9631 pw.print(" * Sticky action "); pw.print(ent.getKey());
9632 if (dumpAll) {
9633 pw.println(":");
9634 ArrayList<Intent> intents = ent.getValue();
9635 final int N = intents.size();
9636 for (int i=0; i<N; i++) {
9637 sb.setLength(0);
9638 sb.append(" Intent: ");
9639 intents.get(i).toShortString(sb, false, true, false, false);
9640 pw.println(sb.toString());
9641 Bundle bundle = intents.get(i).getExtras();
9642 if (bundle != null) {
9643 pw.print(" ");
9644 pw.println(bundle.toString());
9645 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009646 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009647 } else {
9648 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009649 }
9650 }
9651 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009652 }
9653
Dianne Hackborn786b4402012-08-27 15:14:02 -07009654 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009655 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009656 for (BroadcastQueue queue : mBroadcastQueues) {
9657 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9658 + queue.mBroadcastsScheduled);
9659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009660 pw.println(" mHandler:");
9661 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009662 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009663 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009664
9665 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009666 }
9667
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009668 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009669 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009670 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009671
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009672 ItemMatcher matcher = new ItemMatcher();
9673 matcher.build(args, opti);
9674
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009675 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009676
9677 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009678
9679 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009680 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009681 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009682 ContentProviderRecord r = mLaunchingProviders.get(i);
9683 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9684 continue;
9685 }
9686 if (!printed) {
9687 if (needSep) pw.println(" ");
9688 needSep = true;
9689 pw.println(" Launching content providers:");
9690 printed = true;
9691 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009692 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009693 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009694 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009695 }
9696
9697 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009698 if (needSep) pw.println();
9699 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009700 pw.println("Granted Uri Permissions:");
9701 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9702 int uid = mGrantedUriPermissions.keyAt(i);
9703 HashMap<Uri, UriPermission> perms
9704 = mGrantedUriPermissions.valueAt(i);
9705 pw.print(" * UID "); pw.print(uid);
9706 pw.println(" holds:");
9707 for (UriPermission perm : perms.values()) {
9708 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009709 if (dumpAll) {
9710 perm.dump(pw, " ");
9711 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009712 }
9713 }
9714 needSep = true;
9715 }
9716
9717 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009718 }
9719
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009720 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009721 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009722 boolean needSep = false;
9723
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009724 if (mIntentSenderRecords.size() > 0) {
9725 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009726 Iterator<WeakReference<PendingIntentRecord>> it
9727 = mIntentSenderRecords.values().iterator();
9728 while (it.hasNext()) {
9729 WeakReference<PendingIntentRecord> ref = it.next();
9730 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009731 if (dumpPackage != null && (rec == null
9732 || !dumpPackage.equals(rec.key.packageName))) {
9733 continue;
9734 }
9735 if (!printed) {
9736 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9737 printed = true;
9738 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009739 needSep = true;
9740 if (rec != null) {
9741 pw.print(" * "); pw.println(rec);
9742 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009743 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009744 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009745 } else {
9746 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009747 }
9748 }
9749 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009750
9751 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009752 }
9753
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009754 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009755 String prefix, String label, boolean complete, boolean brief, boolean client,
9756 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009757 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009758 boolean needNL = false;
9759 final String innerPrefix = prefix + " ";
9760 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009761 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009762 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009763 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9764 continue;
9765 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009766 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009767 if (needNL) {
9768 pw.println(" ");
9769 needNL = false;
9770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009771 if (lastTask != r.task) {
9772 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009773 pw.print(prefix);
9774 pw.print(full ? "* " : " ");
9775 pw.println(lastTask);
9776 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009777 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009778 } else if (complete) {
9779 // Complete + brief == give a summary. Isn't that obvious?!?
9780 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009781 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009782 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009783 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009785 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009786 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9787 pw.print(" #"); pw.print(i); pw.print(": ");
9788 pw.println(r);
9789 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009790 r.dump(pw, innerPrefix);
9791 } else if (complete) {
9792 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009793 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009794 if (r.app != null) {
9795 pw.print(innerPrefix); pw.println(r.app);
9796 }
9797 }
9798 if (client && r.app != null && r.app.thread != null) {
9799 // flush anything that is already in the PrintWriter since the thread is going
9800 // to write to the file descriptor directly
9801 pw.flush();
9802 try {
9803 TransferPipe tp = new TransferPipe();
9804 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009805 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9806 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009807 // Short timeout, since blocking here can
9808 // deadlock with the application.
9809 tp.go(fd, 2000);
9810 } finally {
9811 tp.kill();
9812 }
9813 } catch (IOException e) {
9814 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9815 } catch (RemoteException e) {
9816 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9817 }
9818 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009820 }
9821 }
9822
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009823 private static String buildOomTag(String prefix, String space, int val, int base) {
9824 if (val == base) {
9825 if (space == null) return prefix;
9826 return prefix + " ";
9827 }
9828 return prefix + "+" + Integer.toString(val-base);
9829 }
9830
9831 private static final int dumpProcessList(PrintWriter pw,
9832 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009833 String prefix, String normalLabel, String persistentLabel,
9834 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009835 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009836 final int N = list.size()-1;
9837 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009838 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009839 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9840 continue;
9841 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009842 pw.println(String.format("%s%s #%2d: %s",
9843 prefix, (r.persistent ? persistentLabel : normalLabel),
9844 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009845 if (r.persistent) {
9846 numPers++;
9847 }
9848 }
9849 return numPers;
9850 }
9851
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009852 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009853 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009854 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009855 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009856
Dianne Hackborn905577f2011-09-07 18:31:28 -07009857 ArrayList<Pair<ProcessRecord, Integer>> list
9858 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9859 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009860 ProcessRecord r = origList.get(i);
9861 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9862 continue;
9863 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009864 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9865 }
9866
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009867 if (list.size() <= 0) {
9868 return false;
9869 }
9870
Dianne Hackborn905577f2011-09-07 18:31:28 -07009871 Comparator<Pair<ProcessRecord, Integer>> comparator
9872 = new Comparator<Pair<ProcessRecord, Integer>>() {
9873 @Override
9874 public int compare(Pair<ProcessRecord, Integer> object1,
9875 Pair<ProcessRecord, Integer> object2) {
9876 if (object1.first.setAdj != object2.first.setAdj) {
9877 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9878 }
9879 if (object1.second.intValue() != object2.second.intValue()) {
9880 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9881 }
9882 return 0;
9883 }
9884 };
9885
9886 Collections.sort(list, comparator);
9887
Dianne Hackborn287952c2010-09-22 22:34:31 -07009888 final long curRealtime = SystemClock.elapsedRealtime();
9889 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9890 final long curUptime = SystemClock.uptimeMillis();
9891 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9892
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009893 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009894 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009895 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009896 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009897 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009898 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9899 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009900 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9901 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009902 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9903 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009904 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9905 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009906 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009907 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009908 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9909 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9910 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9911 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9912 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9913 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9914 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9915 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009916 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9917 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009918 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9919 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009920 } else {
9921 oomAdj = Integer.toString(r.setAdj);
9922 }
9923 String schedGroup;
9924 switch (r.setSchedGroup) {
9925 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9926 schedGroup = "B";
9927 break;
9928 case Process.THREAD_GROUP_DEFAULT:
9929 schedGroup = "F";
9930 break;
9931 default:
9932 schedGroup = Integer.toString(r.setSchedGroup);
9933 break;
9934 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009935 String foreground;
9936 if (r.foregroundActivities) {
9937 foreground = "A";
9938 } else if (r.foregroundServices) {
9939 foreground = "S";
9940 } else {
9941 foreground = " ";
9942 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009943 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009944 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009945 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9946 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009947 if (r.adjSource != null || r.adjTarget != null) {
9948 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009949 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009950 if (r.adjTarget instanceof ComponentName) {
9951 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9952 } else if (r.adjTarget != null) {
9953 pw.print(r.adjTarget.toString());
9954 } else {
9955 pw.print("{null}");
9956 }
9957 pw.print("<=");
9958 if (r.adjSource instanceof ProcessRecord) {
9959 pw.print("Proc{");
9960 pw.print(((ProcessRecord)r.adjSource).toShortString());
9961 pw.println("}");
9962 } else if (r.adjSource != null) {
9963 pw.println(r.adjSource.toString());
9964 } else {
9965 pw.println("{null}");
9966 }
9967 }
9968 if (inclDetails) {
9969 pw.print(prefix);
9970 pw.print(" ");
9971 pw.print("oom: max="); pw.print(r.maxAdj);
9972 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009973 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009974 pw.print(" curRaw="); pw.print(r.curRawAdj);
9975 pw.print(" setRaw="); pw.print(r.setRawAdj);
9976 pw.print(" cur="); pw.print(r.curAdj);
9977 pw.print(" set="); pw.println(r.setAdj);
9978 pw.print(prefix);
9979 pw.print(" ");
9980 pw.print("keeping="); pw.print(r.keeping);
9981 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009982 pw.print(" empty="); pw.print(r.empty);
9983 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009984
9985 if (!r.keeping) {
9986 if (r.lastWakeTime != 0) {
9987 long wtime;
9988 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9989 synchronized (stats) {
9990 wtime = stats.getProcessWakeTime(r.info.uid,
9991 r.pid, curRealtime);
9992 }
9993 long timeUsed = wtime - r.lastWakeTime;
9994 pw.print(prefix);
9995 pw.print(" ");
9996 pw.print("keep awake over ");
9997 TimeUtils.formatDuration(realtimeSince, pw);
9998 pw.print(" used ");
9999 TimeUtils.formatDuration(timeUsed, pw);
10000 pw.print(" (");
10001 pw.print((timeUsed*100)/realtimeSince);
10002 pw.println("%)");
10003 }
10004 if (r.lastCpuTime != 0) {
10005 long timeUsed = r.curCpuTime - r.lastCpuTime;
10006 pw.print(prefix);
10007 pw.print(" ");
10008 pw.print("run cpu over ");
10009 TimeUtils.formatDuration(uptimeSince, pw);
10010 pw.print(" used ");
10011 TimeUtils.formatDuration(timeUsed, pw);
10012 pw.print(" (");
10013 pw.print((timeUsed*100)/uptimeSince);
10014 pw.println("%)");
10015 }
10016 }
10017 }
10018 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -080010019 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -070010020 }
10021
Dianne Hackbornb437e092011-08-05 17:50:29 -070010022 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010023 ArrayList<ProcessRecord> procs;
10024 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010025 if (args != null && args.length > start
10026 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010027 procs = new ArrayList<ProcessRecord>();
10028 int pid = -1;
10029 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010030 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010031 } catch (NumberFormatException e) {
10032
10033 }
10034 for (int i=mLruProcesses.size()-1; i>=0; i--) {
10035 ProcessRecord proc = mLruProcesses.get(i);
10036 if (proc.pid == pid) {
10037 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010038 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010039 procs.add(proc);
10040 }
10041 }
10042 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010043 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010044 return null;
10045 }
10046 } else {
10047 procs = new ArrayList<ProcessRecord>(mLruProcesses);
10048 }
10049 }
10050 return procs;
10051 }
10052
10053 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
10054 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010055 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010056 if (procs == null) {
10057 return;
10058 }
10059
10060 long uptime = SystemClock.uptimeMillis();
10061 long realtime = SystemClock.elapsedRealtime();
10062 pw.println("Applications Graphics Acceleration Info:");
10063 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10064
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010065 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10066 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010067 if (r.thread != null) {
10068 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
10069 pw.flush();
10070 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010071 TransferPipe tp = new TransferPipe();
10072 try {
10073 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
10074 tp.go(fd);
10075 } finally {
10076 tp.kill();
10077 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010078 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010079 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010080 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -070010081 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010082 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -070010083 pw.flush();
10084 }
10085 }
10086 }
Chet Haase9c1e23b2011-03-24 10:51:31 -070010087 }
10088
Jeff Brown6754ba22011-12-14 20:20:01 -080010089 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
10090 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
10091 if (procs == null) {
10092 return;
10093 }
10094
10095 pw.println("Applications Database Info:");
10096
10097 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10098 ProcessRecord r = procs.get(i);
10099 if (r.thread != null) {
10100 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10101 pw.flush();
10102 try {
10103 TransferPipe tp = new TransferPipe();
10104 try {
10105 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10106 tp.go(fd);
10107 } finally {
10108 tp.kill();
10109 }
10110 } catch (IOException e) {
10111 pw.println("Failure while dumping the app: " + r);
10112 pw.flush();
10113 } catch (RemoteException e) {
10114 pw.println("Got a RemoteException while dumping the app " + r);
10115 pw.flush();
10116 }
10117 }
10118 }
10119 }
10120
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010121 final static class MemItem {
10122 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010123 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010124 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010125 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010126 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010127
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010128 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010129 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010130 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010131 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010132 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010133 }
10134 }
10135
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010136 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010137 boolean sort) {
10138 if (sort) {
10139 Collections.sort(items, new Comparator<MemItem>() {
10140 @Override
10141 public int compare(MemItem lhs, MemItem rhs) {
10142 if (lhs.pss < rhs.pss) {
10143 return 1;
10144 } else if (lhs.pss > rhs.pss) {
10145 return -1;
10146 }
10147 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010148 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010149 });
10150 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010151
10152 for (int i=0; i<items.size(); i++) {
10153 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010154 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010155 if (mi.subitems != null) {
10156 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10157 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010158 }
10159 }
10160
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010161 // These are in KB.
10162 static final long[] DUMP_MEM_BUCKETS = new long[] {
10163 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10164 120*1024, 160*1024, 200*1024,
10165 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10166 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10167 };
10168
Dianne Hackborn672342c2011-11-29 11:29:02 -080010169 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10170 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010171 int start = label.lastIndexOf('.');
10172 if (start >= 0) start++;
10173 else start = 0;
10174 int end = label.length();
10175 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10176 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10177 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10178 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010179 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010180 out.append(label, start, end);
10181 return;
10182 }
10183 }
10184 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010185 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010186 out.append(label, start, end);
10187 }
10188
10189 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10190 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10191 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10192 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10193 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10194 };
10195 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10196 "System", "Persistent", "Foreground",
10197 "Visible", "Perceptible", "Heavy Weight",
10198 "Backup", "A Services", "Home", "Previous",
10199 "B Services", "Background"
10200 };
10201
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010202 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010203 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010204 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010205 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010206 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010207
10208 int opti = 0;
10209 while (opti < args.length) {
10210 String opt = args[opti];
10211 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10212 break;
10213 }
10214 opti++;
10215 if ("-a".equals(opt)) {
10216 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010217 } else if ("--oom".equals(opt)) {
10218 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010219 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010220 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010221 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010222 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010223 pw.println("If [process] is specified it can be the name or ");
10224 pw.println("pid of a specific process to dump.");
10225 return;
10226 } else {
10227 pw.println("Unknown argument: " + opt + "; use -h for help");
10228 }
10229 }
10230
10231 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010232 if (procs == null) {
10233 return;
10234 }
10235
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010236 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010237 long uptime = SystemClock.uptimeMillis();
10238 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010239
10240 if (procs.size() == 1 || isCheckinRequest) {
10241 dumpAll = true;
10242 }
10243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010244 if (isCheckinRequest) {
10245 // short checkin version
10246 pw.println(uptime + "," + realtime);
10247 pw.flush();
10248 } else {
10249 pw.println("Applications Memory Usage (kB):");
10250 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10251 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010252
Dianne Hackbornb437e092011-08-05 17:50:29 -070010253 String[] innerArgs = new String[args.length-opti];
10254 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10255
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010256 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10257 long nativePss=0, dalvikPss=0, otherPss=0;
10258 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10259
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010260 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10261 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10262 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010263
10264 long totalPss = 0;
10265
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010266 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10267 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010268 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010269 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010270 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10271 pw.flush();
10272 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010273 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010274 if (dumpAll) {
10275 try {
10276 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10277 } catch (RemoteException e) {
10278 if (!isCheckinRequest) {
10279 pw.println("Got RemoteException!");
10280 pw.flush();
10281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010282 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010283 } else {
10284 mi = new Debug.MemoryInfo();
10285 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010286 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010287
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010288 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010289 long myTotalPss = mi.getTotalPss();
10290 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010291 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010292 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010293 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010294
10295 nativePss += mi.nativePss;
10296 dalvikPss += mi.dalvikPss;
10297 otherPss += mi.otherPss;
10298 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10299 long mem = mi.getOtherPss(j);
10300 miscPss[j] += mem;
10301 otherPss -= mem;
10302 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010303
10304 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010305 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10306 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010307 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010308 if (oomProcs[oomIndex] == null) {
10309 oomProcs[oomIndex] = new ArrayList<MemItem>();
10310 }
10311 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010312 break;
10313 }
10314 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010316 }
10317 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010318
10319 if (!isCheckinRequest && procs.size() > 1) {
10320 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10321
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010322 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10323 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10324 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010325 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010326 String label = Debug.MemoryInfo.getOtherLabel(j);
10327 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010328 }
10329
Dianne Hackbornb437e092011-08-05 17:50:29 -070010330 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10331 for (int j=0; j<oomPss.length; j++) {
10332 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010333 String label = DUMP_MEM_OOM_LABEL[j];
10334 MemItem item = new MemItem(label, label, oomPss[j],
10335 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010336 item.subitems = oomProcs[j];
10337 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010338 }
10339 }
10340
Dianne Hackborn672342c2011-11-29 11:29:02 -080010341 if (outTag != null || outStack != null) {
10342 if (outTag != null) {
10343 appendMemBucket(outTag, totalPss, "total", false);
10344 }
10345 if (outStack != null) {
10346 appendMemBucket(outStack, totalPss, "total", true);
10347 }
10348 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010349 for (int i=0; i<oomMems.size(); i++) {
10350 MemItem miCat = oomMems.get(i);
10351 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10352 continue;
10353 }
10354 if (miCat.id < ProcessList.SERVICE_ADJ
10355 || miCat.id == ProcessList.HOME_APP_ADJ
10356 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010357 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10358 outTag.append(" / ");
10359 }
10360 if (outStack != null) {
10361 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10362 if (firstLine) {
10363 outStack.append(":");
10364 firstLine = false;
10365 }
10366 outStack.append("\n\t at ");
10367 } else {
10368 outStack.append("$");
10369 }
10370 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010371 for (int j=0; j<miCat.subitems.size(); j++) {
10372 MemItem mi = miCat.subitems.get(j);
10373 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010374 if (outTag != null) {
10375 outTag.append(" ");
10376 }
10377 if (outStack != null) {
10378 outStack.append("$");
10379 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010380 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010381 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10382 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10383 }
10384 if (outStack != null) {
10385 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10386 }
10387 }
10388 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10389 outStack.append("(");
10390 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10391 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10392 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10393 outStack.append(":");
10394 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10395 }
10396 }
10397 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010398 }
10399 }
10400 }
10401 }
10402
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010403 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010404 pw.println();
10405 pw.println("Total PSS by process:");
10406 dumpMemItems(pw, " ", procMems, true);
10407 pw.println();
10408 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010409 pw.println("Total PSS by OOM adjustment:");
10410 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010411 if (!oomOnly) {
10412 PrintWriter out = categoryPw != null ? categoryPw : pw;
10413 out.println();
10414 out.println("Total PSS by category:");
10415 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010416 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010417 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010418 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010419 final int[] SINGLE_LONG_FORMAT = new int[] {
10420 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10421 };
10422 long[] longOut = new long[1];
10423 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10424 SINGLE_LONG_FORMAT, null, longOut, null);
10425 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10426 longOut[0] = 0;
10427 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10428 SINGLE_LONG_FORMAT, null, longOut, null);
10429 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10430 longOut[0] = 0;
10431 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10432 SINGLE_LONG_FORMAT, null, longOut, null);
10433 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10434 longOut[0] = 0;
10435 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10436 SINGLE_LONG_FORMAT, null, longOut, null);
10437 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10438 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10439 pw.print(shared); pw.println(" kB");
10440 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10441 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010443 }
10444
10445 /**
10446 * Searches array of arguments for the specified string
10447 * @param args array of argument strings
10448 * @param value value to search for
10449 * @return true if the value is contained in the array
10450 */
10451 private static boolean scanArgs(String[] args, String value) {
10452 if (args != null) {
10453 for (String arg : args) {
10454 if (value.equals(arg)) {
10455 return true;
10456 }
10457 }
10458 }
10459 return false;
10460 }
10461
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010462 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10463 ContentProviderRecord cpr, boolean always) {
10464 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10465
10466 if (!inLaunching || always) {
10467 synchronized (cpr) {
10468 cpr.launchingApp = null;
10469 cpr.notifyAll();
10470 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010471 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010472 String names[] = cpr.info.authority.split(";");
10473 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010474 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010475 }
10476 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010477
10478 for (int i=0; i<cpr.connections.size(); i++) {
10479 ContentProviderConnection conn = cpr.connections.get(i);
10480 if (conn.waiting) {
10481 // If this connection is waiting for the provider, then we don't
10482 // need to mess with its process unless we are always removing
10483 // or for some reason the provider is not currently launching.
10484 if (inLaunching && !always) {
10485 continue;
10486 }
10487 }
10488 ProcessRecord capp = conn.client;
10489 conn.dead = true;
10490 if (conn.stableCount > 0) {
10491 if (!capp.persistent && capp.thread != null
10492 && capp.pid != 0
10493 && capp.pid != MY_PID) {
10494 Slog.i(TAG, "Kill " + capp.processName
10495 + " (pid " + capp.pid + "): provider " + cpr.info.name
10496 + " in dying process " + (proc != null ? proc.processName : "??"));
10497 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10498 capp.processName, capp.setAdj, "dying provider "
10499 + cpr.name.toShortString());
10500 Process.killProcessQuiet(capp.pid);
10501 }
10502 } else if (capp.thread != null && conn.provider.provider != null) {
10503 try {
10504 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10505 } catch (RemoteException e) {
10506 }
10507 // In the protocol here, we don't expect the client to correctly
10508 // clean up this connection, we'll just remove it.
10509 cpr.connections.remove(i);
10510 conn.client.conProviders.remove(conn);
10511 }
10512 }
10513
10514 if (inLaunching && always) {
10515 mLaunchingProviders.remove(cpr);
10516 }
10517 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010518 }
10519
10520 /**
10521 * Main code for cleaning up a process when it has gone away. This is
10522 * called both as a result of the process dying, or directly when stopping
10523 * a process when running in single process mode.
10524 */
10525 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010526 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010527 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010528 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010529 }
10530
Dianne Hackborn36124872009-10-08 16:22:03 -070010531 mProcessesToGc.remove(app);
10532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010533 // Dismiss any open dialogs.
10534 if (app.crashDialog != null) {
10535 app.crashDialog.dismiss();
10536 app.crashDialog = null;
10537 }
10538 if (app.anrDialog != null) {
10539 app.anrDialog.dismiss();
10540 app.anrDialog = null;
10541 }
10542 if (app.waitDialog != null) {
10543 app.waitDialog.dismiss();
10544 app.waitDialog = null;
10545 }
10546
10547 app.crashing = false;
10548 app.notResponding = false;
10549
10550 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010551 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010552 app.thread = null;
10553 app.forcingToForeground = null;
10554 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010555 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010556 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010557 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010558
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010559 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010560
10561 boolean restart = false;
10562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010563 // Remove published content providers.
10564 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010565 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010566 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010567 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010568
10569 final boolean always = app.bad || !allowRestart;
10570 if (removeDyingProviderLocked(app, cpr, always) || always) {
10571 // We left the provider in the launching list, need to
10572 // restart it.
10573 restart = true;
10574 }
10575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010576 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010577 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010578 }
10579 app.pubProviders.clear();
10580 }
10581
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010582 // Take care of any launching providers waiting for this process.
10583 if (checkAppInLaunchingProvidersLocked(app, false)) {
10584 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010585 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010587 // Unregister from connected content providers.
10588 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010589 for (int i=0; i<app.conProviders.size(); i++) {
10590 ContentProviderConnection conn = app.conProviders.get(i);
10591 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010592 }
10593 app.conProviders.clear();
10594 }
10595
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010596 // At this point there may be remaining entries in mLaunchingProviders
10597 // where we were the only one waiting, so they are no longer of use.
10598 // Look for these and clean up if found.
10599 // XXX Commented out for now. Trying to figure out a way to reproduce
10600 // the actual situation to identify what is actually going on.
10601 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010602 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010603 ContentProviderRecord cpr = (ContentProviderRecord)
10604 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010605 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010606 synchronized (cpr) {
10607 cpr.launchingApp = null;
10608 cpr.notifyAll();
10609 }
10610 }
10611 }
10612 }
10613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010614 skipCurrentReceiverLocked(app);
10615
10616 // Unregister any receivers.
10617 if (app.receivers.size() > 0) {
10618 Iterator<ReceiverList> it = app.receivers.iterator();
10619 while (it.hasNext()) {
10620 removeReceiverLocked(it.next());
10621 }
10622 app.receivers.clear();
10623 }
10624
Christopher Tate181fafa2009-05-14 11:12:14 -070010625 // If the app is undergoing backup, tell the backup manager about it
10626 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010627 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010628 try {
10629 IBackupManager bm = IBackupManager.Stub.asInterface(
10630 ServiceManager.getService(Context.BACKUP_SERVICE));
10631 bm.agentDisconnected(app.info.packageName);
10632 } catch (RemoteException e) {
10633 // can't happen; backup manager is local
10634 }
10635 }
10636
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010637 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10638 ProcessChangeItem item = mPendingProcessChanges.get(i);
10639 if (item.pid == app.pid) {
10640 mPendingProcessChanges.remove(i);
10641 mAvailProcessChanges.add(item);
10642 }
10643 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010644 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010646 // If the caller is restarting this app, then leave it in its
10647 // current lists and let the caller take care of it.
10648 if (restarting) {
10649 return;
10650 }
10651
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010652 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010653 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010654 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010655 mProcessNames.remove(app.processName, app.uid);
10656 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010657 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010658 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10659 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010660 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010662 } else if (!app.removed) {
10663 // This app is persistent, so we need to keep its record around.
10664 // If it is not already on the pending app list, add it there
10665 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010666 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10667 mPersistentStartingProcesses.add(app);
10668 restart = true;
10669 }
10670 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010671 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10672 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010673 mProcessesOnHold.remove(app);
10674
The Android Open Source Project4df24232009-03-05 14:34:35 -080010675 if (app == mHomeProcess) {
10676 mHomeProcess = null;
10677 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010678 if (app == mPreviousProcess) {
10679 mPreviousProcess = null;
10680 }
10681
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010682 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010683 // We have components that still need to be running in the
10684 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010685 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010686 startProcessLocked(app, "restart", app.processName);
10687 } else if (app.pid > 0 && app.pid != MY_PID) {
10688 // Goodbye!
10689 synchronized (mPidsSelfLocked) {
10690 mPidsSelfLocked.remove(app.pid);
10691 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10692 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010693 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010694 }
10695 }
10696
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010697 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10698 // Look through the content providers we are waiting to have launched,
10699 // and if any run in this process then either schedule a restart of
10700 // the process or kill the client waiting for it if this process has
10701 // gone bad.
10702 int NL = mLaunchingProviders.size();
10703 boolean restart = false;
10704 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010705 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010706 if (cpr.launchingApp == app) {
10707 if (!alwaysBad && !app.bad) {
10708 restart = true;
10709 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010710 removeDyingProviderLocked(app, cpr, true);
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010711 // cpr should have been removed from mLaunchingProviders
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010712 NL = mLaunchingProviders.size();
Vairavan Srinivasan4ee36492012-09-03 17:09:58 -070010713 i--;
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010714 }
10715 }
10716 }
10717 return restart;
10718 }
10719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010720 // =========================================================
10721 // SERVICES
10722 // =========================================================
10723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010724 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10725 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010726 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010727 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010728 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010729 }
10730 }
10731
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010732 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010733 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010734 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010735 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010736 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010737 }
10738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010739 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010740 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010741 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010742 // Refuse possible leaked file descriptors
10743 if (service != null && service.hasFileDescriptors() == true) {
10744 throw new IllegalArgumentException("File descriptors passed in Intent");
10745 }
10746
Amith Yamasani742a6712011-05-04 14:49:28 -070010747 if (DEBUG_SERVICE)
10748 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010749 synchronized(this) {
10750 final int callingPid = Binder.getCallingPid();
10751 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010752 checkValidCaller(callingUid, userId);
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(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010755 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010756 Binder.restoreCallingIdentity(origId);
10757 return res;
10758 }
10759 }
10760
10761 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010762 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010763 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010764 if (DEBUG_SERVICE)
10765 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010766 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010767 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010768 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010769 Binder.restoreCallingIdentity(origId);
10770 return res;
10771 }
10772 }
10773
10774 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010775 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010776 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010777 // Refuse possible leaked file descriptors
10778 if (service != null && service.hasFileDescriptors() == true) {
10779 throw new IllegalArgumentException("File descriptors passed in Intent");
10780 }
10781
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010782 checkValidCaller(Binder.getCallingUid(), userId);
10783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010784 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010785 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010787 }
10788
10789 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010790 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010791 // Refuse possible leaked file descriptors
10792 if (service != null && service.hasFileDescriptors() == true) {
10793 throw new IllegalArgumentException("File descriptors passed in Intent");
10794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010795 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010796 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010798 }
10799
10800 public boolean stopServiceToken(ComponentName className, IBinder token,
10801 int startId) {
10802 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010803 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010805 }
10806
10807 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010808 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010809 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010810 mServices.setServiceForegroundLocked(className, token, id, notification,
10811 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010812 }
10813 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010814
Dianne Hackborn41203752012-08-31 14:05:51 -070010815 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10816 boolean requireFull, String name, String callerPackage) {
10817 synchronized(this) {
10818 return handleIncomingUserLocked(callingPid, callingUid, userId, allowAll,
10819 requireFull, name, callerPackage);
10820 }
10821 }
10822
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010823 int handleIncomingUserLocked(int callingPid, int callingUid, int userId, boolean allowAll,
10824 boolean requireFull, String name, String callerPackage) {
10825 final int callingUserId = UserHandle.getUserId(callingUid);
10826 if (callingUserId != userId) {
10827 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10828 if ((requireFull || checkComponentPermission(
10829 android.Manifest.permission.INTERACT_ACROSS_USERS,
10830 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10831 && checkComponentPermission(
10832 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10833 callingPid, callingUid, -1, true)
10834 != PackageManager.PERMISSION_GRANTED) {
10835 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10836 // In this case, they would like to just execute as their
10837 // owner user instead of failing.
10838 userId = callingUserId;
10839 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010840 StringBuilder builder = new StringBuilder(128);
10841 builder.append("Permission Denial: ");
10842 builder.append(name);
10843 if (callerPackage != null) {
10844 builder.append(" from ");
10845 builder.append(callerPackage);
10846 }
10847 builder.append(" asks to run as user ");
10848 builder.append(userId);
10849 builder.append(" but is calling from user ");
10850 builder.append(UserHandle.getUserId(callingUid));
10851 builder.append("; this requires ");
10852 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10853 if (!requireFull) {
10854 builder.append("or");
10855 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10856 }
10857 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010858 Slog.w(TAG, msg);
10859 throw new SecurityException(msg);
10860 }
10861 }
10862 }
10863 if (userId == UserHandle.USER_CURRENT
10864 || userId == UserHandle.USER_CURRENT_OR_SELF) {
10865 userId = mCurrentUserId;
10866 }
10867 if (!allowAll && userId < 0) {
10868 throw new IllegalArgumentException(
10869 "Call does not support special user #" + userId);
10870 }
10871 }
10872 return userId;
10873 }
10874
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010875 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10876 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010877 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010878 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010879 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10880 if (ActivityManager.checkUidPermission(
10881 android.Manifest.permission.INTERACT_ACROSS_USERS,
10882 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10883 ComponentName comp = new ComponentName(aInfo.packageName, className);
10884 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10885 + " requests FLAG_SINGLE_USER, but app does not hold "
10886 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10887 Slog.w(TAG, msg);
10888 throw new SecurityException(msg);
10889 }
10890 result = true;
10891 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010892 } else if (componentProcessName == aInfo.packageName) {
10893 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10894 } else if ("system".equals(componentProcessName)) {
10895 result = true;
10896 }
10897 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010898 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10899 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010900 }
10901 return result;
10902 }
10903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010904 public int bindService(IApplicationThread caller, IBinder token,
10905 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010906 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010907 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010908 // Refuse possible leaked file descriptors
10909 if (service != null && service.hasFileDescriptors() == true) {
10910 throw new IllegalArgumentException("File descriptors passed in Intent");
10911 }
10912
10913 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010914 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10915 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010916 }
10917 }
10918
10919 public boolean unbindService(IServiceConnection connection) {
10920 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010921 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010923 }
10924
10925 public void publishService(IBinder token, Intent intent, IBinder service) {
10926 // Refuse possible leaked file descriptors
10927 if (intent != null && intent.hasFileDescriptors() == true) {
10928 throw new IllegalArgumentException("File descriptors passed in Intent");
10929 }
10930
10931 synchronized(this) {
10932 if (!(token instanceof ServiceRecord)) {
10933 throw new IllegalArgumentException("Invalid service token");
10934 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010935 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010936 }
10937 }
10938
10939 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10940 // Refuse possible leaked file descriptors
10941 if (intent != null && intent.hasFileDescriptors() == true) {
10942 throw new IllegalArgumentException("File descriptors passed in Intent");
10943 }
10944
10945 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010946 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010947 }
10948 }
10949
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010950 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010951 synchronized(this) {
10952 if (!(token instanceof ServiceRecord)) {
10953 throw new IllegalArgumentException("Invalid service token");
10954 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010955 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010957 }
10958
10959 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010960 // BACKUP AND RESTORE
10961 // =========================================================
10962
10963 // Cause the target app to be launched if necessary and its backup agent
10964 // instantiated. The backup agent will invoke backupAgentCreated() on the
10965 // activity manager to announce its creation.
10966 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010967 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010968 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10969
10970 synchronized(this) {
10971 // !!! TODO: currently no check here that we're already bound
10972 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10973 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10974 synchronized (stats) {
10975 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10976 }
10977
Dianne Hackborne7f97212011-02-24 14:40:20 -080010978 // Backup agent is now in use, its package can't be stopped.
10979 try {
10980 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010981 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080010982 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010983 } catch (IllegalArgumentException e) {
10984 Slog.w(TAG, "Failed trying to unstop package "
10985 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010986 }
10987
Christopher Tate181fafa2009-05-14 11:12:14 -070010988 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070010989 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
10990 ? new ComponentName(app.packageName, app.backupAgentName)
10991 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070010992 // startProcessLocked() returns existing proc's record if it's already running
10993 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010994 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010995 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010996 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010997 return false;
10998 }
10999
11000 r.app = proc;
11001 mBackupTarget = r;
11002 mBackupAppName = app.packageName;
11003
Christopher Tate6fa95972009-06-05 18:43:55 -070011004 // Try not to kill the process during backup
11005 updateOomAdjLocked(proc);
11006
Christopher Tate181fafa2009-05-14 11:12:14 -070011007 // If the process is already attached, schedule the creation of the backup agent now.
11008 // If it is not yet live, this will be done when it attaches to the framework.
11009 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011010 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070011011 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011012 proc.thread.scheduleCreateBackupAgent(app,
11013 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070011014 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070011015 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070011016 }
11017 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011018 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070011019 }
11020 // Invariants: at this point, the target app process exists and the application
11021 // is either already running or in the process of coming up. mBackupTarget and
11022 // mBackupAppName describe the app, so that when it binds back to the AM we
11023 // know that it's scheduled for a backup-agent operation.
11024 }
11025
11026 return true;
11027 }
11028
11029 // A backup agent has just come up
11030 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011031 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070011032 + " = " + agent);
11033
11034 synchronized(this) {
11035 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011036 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070011037 return;
11038 }
Dianne Hackborn06740692010-09-22 22:46:21 -070011039 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011040
Dianne Hackborn06740692010-09-22 22:46:21 -070011041 long oldIdent = Binder.clearCallingIdentity();
11042 try {
11043 IBackupManager bm = IBackupManager.Stub.asInterface(
11044 ServiceManager.getService(Context.BACKUP_SERVICE));
11045 bm.agentConnected(agentPackageName, agent);
11046 } catch (RemoteException e) {
11047 // can't happen; the backup manager service is local
11048 } catch (Exception e) {
11049 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
11050 e.printStackTrace();
11051 } finally {
11052 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070011053 }
11054 }
11055
11056 // done with this agent
11057 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011058 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070011059 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011060 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070011061 return;
11062 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011063
11064 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070011065 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011066 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070011067 return;
11068 }
11069
Christopher Tate181fafa2009-05-14 11:12:14 -070011070 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011071 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070011072 return;
11073 }
11074
Christopher Tate6fa95972009-06-05 18:43:55 -070011075 ProcessRecord proc = mBackupTarget.app;
11076 mBackupTarget = null;
11077 mBackupAppName = null;
11078
11079 // Not backing this app up any more; reset its OOM adjustment
11080 updateOomAdjLocked(proc);
11081
Christopher Tatec7b31e32009-06-10 15:49:30 -070011082 // If the app crashed during backup, 'thread' will be null here
11083 if (proc.thread != null) {
11084 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040011085 proc.thread.scheduleDestroyBackupAgent(appInfo,
11086 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070011087 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011088 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070011089 e.printStackTrace();
11090 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011091 }
Christopher Tate181fafa2009-05-14 11:12:14 -070011092 }
11093 }
11094 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011095 // BROADCASTS
11096 // =========================================================
11097
Josh Bartel7f208742010-02-25 11:01:44 -060011098 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011099 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011100 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011101 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11102 if (stickies == null) {
11103 return cur;
11104 }
11105 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011106 if (list == null) {
11107 return cur;
11108 }
11109 int N = list.size();
11110 for (int i=0; i<N; i++) {
11111 Intent intent = list.get(i);
11112 if (filter.match(resolver, intent, true, TAG) >= 0) {
11113 if (cur == null) {
11114 cur = new ArrayList<Intent>();
11115 }
11116 cur.add(intent);
11117 }
11118 }
11119 return cur;
11120 }
11121
Christopher Tatef46723b2012-01-26 14:19:24 -080011122 boolean isPendingBroadcastProcessLocked(int pid) {
11123 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11124 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011126
Christopher Tatef46723b2012-01-26 14:19:24 -080011127 void skipPendingBroadcastLocked(int pid) {
11128 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11129 for (BroadcastQueue queue : mBroadcastQueues) {
11130 queue.skipPendingBroadcastLocked(pid);
11131 }
11132 }
11133
11134 // The app just attached; send any pending broadcasts that it should receive
11135 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11136 boolean didSomething = false;
11137 for (BroadcastQueue queue : mBroadcastQueues) {
11138 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011139 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011140 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011141 }
11142
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011143 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011144 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011145 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011146 int callingUid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011147 int callingPid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011148 synchronized(this) {
11149 ProcessRecord callerApp = null;
11150 if (caller != null) {
11151 callerApp = getRecordForAppLocked(caller);
11152 if (callerApp == null) {
11153 throw new SecurityException(
11154 "Unable to find app for caller " + caller
11155 + " (pid=" + Binder.getCallingPid()
11156 + ") when registering receiver " + receiver);
11157 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011158 if (callerApp.info.uid != Process.SYSTEM_UID &&
11159 !callerApp.pkgList.contains(callerPackage)) {
11160 throw new SecurityException("Given caller package " + callerPackage
11161 + " is not running in process " + callerApp);
11162 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011163 callingUid = callerApp.info.uid;
Dianne Hackborn20e80982012-08-31 19:00:44 -070011164 callingPid = callerApp.pid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011165 } else {
11166 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011167 callingUid = Binder.getCallingUid();
Dianne Hackborn20e80982012-08-31 19:00:44 -070011168 callingPid = Binder.getCallingPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011169 }
11170
Dianne Hackborn20e80982012-08-31 19:00:44 -070011171 userId = this.handleIncomingUserLocked(callingPid, callingUid, userId,
11172 true, true, "registerReceiver", callerPackage);
11173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011174 List allSticky = null;
11175
11176 // Look for any matching sticky broadcasts...
11177 Iterator actions = filter.actionsIterator();
11178 if (actions != null) {
11179 while (actions.hasNext()) {
11180 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011181 allSticky = getStickiesLocked(action, filter, allSticky,
11182 UserHandle.USER_ALL);
11183 allSticky = getStickiesLocked(action, filter, allSticky,
11184 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011185 }
11186 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011187 allSticky = getStickiesLocked(null, filter, allSticky,
11188 UserHandle.USER_ALL);
11189 allSticky = getStickiesLocked(null, filter, allSticky,
11190 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011191 }
11192
11193 // The first sticky in the list is returned directly back to
11194 // the client.
11195 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11196
Joe Onorato8a9b2202010-02-26 18:56:32 -080011197 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011198 + ": " + sticky);
11199
11200 if (receiver == null) {
11201 return sticky;
11202 }
11203
11204 ReceiverList rl
11205 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11206 if (rl == null) {
Dianne Hackborn20e80982012-08-31 19:00:44 -070011207 rl = new ReceiverList(this, callerApp, callingPid, callingUid,
11208 userId, receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011209 if (rl.app != null) {
11210 rl.app.receivers.add(rl);
11211 } else {
11212 try {
11213 receiver.asBinder().linkToDeath(rl, 0);
11214 } catch (RemoteException e) {
11215 return sticky;
11216 }
11217 rl.linkedToDeath = true;
11218 }
11219 mRegisteredReceivers.put(receiver.asBinder(), rl);
Dianne Hackborn20e80982012-08-31 19:00:44 -070011220 } else if (rl.uid != callingUid) {
11221 throw new IllegalArgumentException(
11222 "Receiver requested to register for uid " + callingUid
11223 + " was previously registered for uid " + rl.uid);
11224 } else if (rl.pid != callingPid) {
11225 throw new IllegalArgumentException(
11226 "Receiver requested to register for pid " + callingPid
11227 + " was previously registered for pid " + rl.pid);
11228 } else if (rl.userId != userId) {
11229 throw new IllegalArgumentException(
11230 "Receiver requested to register for user " + userId
11231 + " was previously registered for user " + rl.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011232 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011233 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
Dianne Hackborn20e80982012-08-31 19:00:44 -070011234 permission, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011235 rl.add(bf);
11236 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011237 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011238 }
11239 mReceiverResolver.addFilter(bf);
11240
11241 // Enqueue broadcasts for all existing stickies that match
11242 // this filter.
11243 if (allSticky != null) {
11244 ArrayList receivers = new ArrayList();
11245 receivers.add(bf);
11246
11247 int N = allSticky.size();
11248 for (int i=0; i<N; i++) {
11249 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011250 BroadcastQueue queue = broadcastQueueForIntent(intent);
11251 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011252 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011253 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011254 queue.enqueueParallelBroadcastLocked(r);
11255 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256 }
11257 }
11258
11259 return sticky;
11260 }
11261 }
11262
11263 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011264 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011265
Christopher Tatef46723b2012-01-26 14:19:24 -080011266 final long origId = Binder.clearCallingIdentity();
11267 try {
11268 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011269
Christopher Tatef46723b2012-01-26 14:19:24 -080011270 synchronized(this) {
11271 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011272 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011273 if (rl != null) {
11274 if (rl.curBroadcast != null) {
11275 BroadcastRecord r = rl.curBroadcast;
11276 final boolean doNext = finishReceiverLocked(
11277 receiver.asBinder(), r.resultCode, r.resultData,
11278 r.resultExtras, r.resultAbort, true);
11279 if (doNext) {
11280 doTrim = true;
11281 r.queue.processNextBroadcast(false);
11282 }
11283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011284
Christopher Tatef46723b2012-01-26 14:19:24 -080011285 if (rl.app != null) {
11286 rl.app.receivers.remove(rl);
11287 }
11288 removeReceiverLocked(rl);
11289 if (rl.linkedToDeath) {
11290 rl.linkedToDeath = false;
11291 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011293 }
11294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011295
Christopher Tatef46723b2012-01-26 14:19:24 -080011296 // If we actually concluded any broadcasts, we might now be able
11297 // to trim the recipients' apps from our working set
11298 if (doTrim) {
11299 trimApplications();
11300 return;
11301 }
11302
11303 } finally {
11304 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011306 }
11307
11308 void removeReceiverLocked(ReceiverList rl) {
11309 mRegisteredReceivers.remove(rl.receiver.asBinder());
11310 int N = rl.size();
11311 for (int i=0; i<N; i++) {
11312 mReceiverResolver.removeFilter(rl.get(i));
11313 }
11314 }
11315
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011316 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011317 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11318 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011319 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011320 try {
11321 r.thread.dispatchPackageBroadcast(cmd, packages);
11322 } catch (RemoteException ex) {
11323 }
11324 }
11325 }
11326 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011327
11328 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11329 int[] users) {
11330 List<ResolveInfo> receivers = null;
11331 try {
11332 HashSet<ComponentName> singleUserReceivers = null;
11333 boolean scannedFirstReceivers = false;
11334 for (int user : users) {
11335 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11336 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
11337 if (newReceivers != null && newReceivers.size() == 0) {
11338 newReceivers = null;
11339 }
11340 if (receivers == null) {
11341 receivers = newReceivers;
11342 } else if (newReceivers != null) {
11343 // We need to concatenate the additional receivers
11344 // found with what we have do far. This would be easy,
11345 // but we also need to de-dup any receivers that are
11346 // singleUser.
11347 if (!scannedFirstReceivers) {
11348 // Collect any single user receivers we had already retrieved.
11349 scannedFirstReceivers = true;
11350 for (int i=0; i<receivers.size(); i++) {
11351 ResolveInfo ri = receivers.get(i);
11352 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11353 ComponentName cn = new ComponentName(
11354 ri.activityInfo.packageName, ri.activityInfo.name);
11355 if (singleUserReceivers == null) {
11356 singleUserReceivers = new HashSet<ComponentName>();
11357 }
11358 singleUserReceivers.add(cn);
11359 }
11360 }
11361 }
11362 // Add the new results to the existing results, tracking
11363 // and de-dupping single user receivers.
11364 for (int i=0; i<newReceivers.size(); i++) {
11365 ResolveInfo ri = receivers.get(i);
11366 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11367 ComponentName cn = new ComponentName(
11368 ri.activityInfo.packageName, ri.activityInfo.name);
11369 if (singleUserReceivers == null) {
11370 singleUserReceivers = new HashSet<ComponentName>();
11371 }
11372 if (!singleUserReceivers.contains(cn)) {
11373 singleUserReceivers.add(cn);
11374 receivers.add(ri);
11375 }
11376 } else {
11377 receivers.add(ri);
11378 }
11379 }
11380 }
11381 }
11382 } catch (RemoteException ex) {
11383 // pm is in same process, this will never happen.
11384 }
11385 return receivers;
11386 }
11387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011388 private final int broadcastIntentLocked(ProcessRecord callerApp,
11389 String callerPackage, Intent intent, String resolvedType,
11390 IIntentReceiver resultTo, int resultCode, String resultData,
11391 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011392 boolean ordered, boolean sticky, int callingPid, int callingUid,
11393 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011394 intent = new Intent(intent);
11395
Dianne Hackborne7f97212011-02-24 14:40:20 -080011396 // By default broadcasts do not go to stopped apps.
11397 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11398
Joe Onorato8a9b2202010-02-26 18:56:32 -080011399 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011400 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011401 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011402 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011403 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011404 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011405
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011406 userId = handleIncomingUserLocked(callingPid, callingUid, userId,
11407 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011408
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011409 // Make sure that the user who is receiving this broadcast is started
11410 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011411 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011412 Slog.w(TAG, "Skipping broadcast of " + intent
11413 + ": user " + userId + " is stopped");
11414 return ActivityManager.BROADCAST_SUCCESS;
11415 }
11416
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011417 /*
11418 * Prevent non-system code (defined here to be non-persistent
11419 * processes) from sending protected broadcasts.
11420 */
11421 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11422 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11423 callingUid == 0) {
11424 // Always okay.
11425 } else if (callerApp == null || !callerApp.persistent) {
11426 try {
11427 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11428 intent.getAction())) {
11429 String msg = "Permission Denial: not allowed to send broadcast "
11430 + intent.getAction() + " from pid="
11431 + callingPid + ", uid=" + callingUid;
11432 Slog.w(TAG, msg);
11433 throw new SecurityException(msg);
11434 }
11435 } catch (RemoteException e) {
11436 Slog.w(TAG, "Remote exception", e);
11437 return ActivityManager.BROADCAST_SUCCESS;
11438 }
11439 }
11440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011441 // Handle special intents: if this broadcast is from the package
11442 // manager about a package being removed, we need to remove all of
11443 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011444 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011445 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011446 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11447 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011448 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011449 || uidRemoved) {
11450 if (checkComponentPermission(
11451 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011452 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011453 == PackageManager.PERMISSION_GRANTED) {
11454 if (uidRemoved) {
11455 final Bundle intentExtras = intent.getExtras();
11456 final int uid = intentExtras != null
11457 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11458 if (uid >= 0) {
11459 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11460 synchronized (bs) {
11461 bs.removeUidStatsLocked(uid);
11462 }
11463 }
11464 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011465 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011466 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011467 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011468 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11469 if (list != null && (list.length > 0)) {
11470 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011471 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011472 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011473 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011474 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011475 }
11476 } else {
11477 Uri data = intent.getData();
11478 String ssp;
11479 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11480 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11481 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011482 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11483 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011484 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011485 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011486 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011487 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011489 }
11490 }
11491 }
11492 } else {
11493 String msg = "Permission Denial: " + intent.getAction()
11494 + " broadcast from " + callerPackage + " (pid=" + callingPid
11495 + ", uid=" + callingUid + ")"
11496 + " requires "
11497 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011498 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011499 throw new SecurityException(msg);
11500 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011501
11502 // Special case for adding a package: by default turn on compatibility
11503 // mode.
11504 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011505 Uri data = intent.getData();
11506 String ssp;
11507 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11508 mCompatModePackages.handlePackageAddedLocked(ssp,
11509 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011511 }
11512
11513 /*
11514 * If this is the time zone changed action, queue up a message that will reset the timezone
11515 * of all currently running processes. This message will get queued up before the broadcast
11516 * happens.
11517 */
11518 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11519 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11520 }
11521
Robert Greenwalt03595d02010-11-02 14:08:23 -070011522 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11523 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11524 }
11525
Robert Greenwalt434203a2010-10-11 16:00:27 -070011526 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11527 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11528 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11529 }
11530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011531 // Add to the sticky list if requested.
11532 if (sticky) {
11533 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11534 callingPid, callingUid)
11535 != PackageManager.PERMISSION_GRANTED) {
11536 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11537 + callingPid + ", uid=" + callingUid
11538 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011539 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011540 throw new SecurityException(msg);
11541 }
11542 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011543 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011544 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011545 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011546 }
11547 if (intent.getComponent() != null) {
11548 throw new SecurityException(
11549 "Sticky broadcasts can't target a specific component");
11550 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011551 // We use userId directly here, since the "all" target is maintained
11552 // as a separate set of sticky broadcasts.
11553 if (userId != UserHandle.USER_ALL) {
11554 // But first, if this is not a broadcast to all users, then
11555 // make sure it doesn't conflict with an existing broadcast to
11556 // all users.
11557 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11558 UserHandle.USER_ALL);
11559 if (stickies != null) {
11560 ArrayList<Intent> list = stickies.get(intent.getAction());
11561 if (list != null) {
11562 int N = list.size();
11563 int i;
11564 for (i=0; i<N; i++) {
11565 if (intent.filterEquals(list.get(i))) {
11566 throw new IllegalArgumentException(
11567 "Sticky broadcast " + intent + " for user "
11568 + userId + " conflicts with existing global broadcast");
11569 }
11570 }
11571 }
11572 }
11573 }
11574 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11575 if (stickies == null) {
11576 stickies = new HashMap<String, ArrayList<Intent>>();
11577 mStickyBroadcasts.put(userId, stickies);
11578 }
11579 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011580 if (list == null) {
11581 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011582 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011583 }
11584 int N = list.size();
11585 int i;
11586 for (i=0; i<N; i++) {
11587 if (intent.filterEquals(list.get(i))) {
11588 // This sticky already exists, replace it.
11589 list.set(i, new Intent(intent));
11590 break;
11591 }
11592 }
11593 if (i >= N) {
11594 list.add(new Intent(intent));
11595 }
11596 }
11597
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011598 int[] users;
11599 if (userId == UserHandle.USER_ALL) {
11600 // Caller wants broadcast to go to all started users.
11601 users = new int[mStartedUsers.size()];
11602 for (int i=0; i<mStartedUsers.size(); i++) {
11603 users[i] = mStartedUsers.keyAt(i);
11604 }
11605 } else {
11606 // Caller wants broadcast to go to one specific user.
11607 users = new int[] {userId};
11608 }
11609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011610 // Figure out who all will receive this broadcast.
11611 List receivers = null;
11612 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011613 // Need to resolve the intent to interested receivers...
11614 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11615 == 0) {
11616 receivers = collectReceiverComponents(intent, resolvedType, users);
11617 }
11618 if (intent.getComponent() == null) {
11619 registeredReceivers = mReceiverResolver.queryIntent(intent,
11620 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011621 }
11622
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011623 final boolean replacePending =
11624 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11625
Joe Onorato8a9b2202010-02-26 18:56:32 -080011626 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011627 + " replacePending=" + replacePending);
11628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011629 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11630 if (!ordered && NR > 0) {
11631 // If we are not serializing this broadcast, then send the
11632 // registered receivers separately so they don't wait for the
11633 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011634 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11635 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011636 callerPackage, callingPid, callingUid, requiredPermission,
11637 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011638 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011639 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011640 TAG, "Enqueueing parallel broadcast " + r);
11641 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011642 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011643 queue.enqueueParallelBroadcastLocked(r);
11644 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011646 registeredReceivers = null;
11647 NR = 0;
11648 }
11649
11650 // Merge into one list.
11651 int ir = 0;
11652 if (receivers != null) {
11653 // A special case for PACKAGE_ADDED: do not allow the package
11654 // being added to see this broadcast. This prevents them from
11655 // using this as a back door to get run as soon as they are
11656 // installed. Maybe in the future we want to have a special install
11657 // broadcast or such for apps, but we'd like to deliberately make
11658 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011659 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011660 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11661 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11662 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011663 Uri data = intent.getData();
11664 if (data != null) {
11665 String pkgName = data.getSchemeSpecificPart();
11666 if (pkgName != null) {
11667 skipPackages = new String[] { pkgName };
11668 }
11669 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011670 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011671 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011672 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011673 if (skipPackages != null && (skipPackages.length > 0)) {
11674 for (String skipPackage : skipPackages) {
11675 if (skipPackage != null) {
11676 int NT = receivers.size();
11677 for (int it=0; it<NT; it++) {
11678 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11679 if (curt.activityInfo.packageName.equals(skipPackage)) {
11680 receivers.remove(it);
11681 it--;
11682 NT--;
11683 }
11684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011685 }
11686 }
11687 }
11688
11689 int NT = receivers != null ? receivers.size() : 0;
11690 int it = 0;
11691 ResolveInfo curt = null;
11692 BroadcastFilter curr = null;
11693 while (it < NT && ir < NR) {
11694 if (curt == null) {
11695 curt = (ResolveInfo)receivers.get(it);
11696 }
11697 if (curr == null) {
11698 curr = registeredReceivers.get(ir);
11699 }
11700 if (curr.getPriority() >= curt.priority) {
11701 // Insert this broadcast record into the final list.
11702 receivers.add(it, curr);
11703 ir++;
11704 curr = null;
11705 it++;
11706 NT++;
11707 } else {
11708 // Skip to the next ResolveInfo in the final list.
11709 it++;
11710 curt = null;
11711 }
11712 }
11713 }
11714 while (ir < NR) {
11715 if (receivers == null) {
11716 receivers = new ArrayList();
11717 }
11718 receivers.add(registeredReceivers.get(ir));
11719 ir++;
11720 }
11721
11722 if ((receivers != null && receivers.size() > 0)
11723 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011724 BroadcastQueue queue = broadcastQueueForIntent(intent);
11725 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011726 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011727 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011728 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011729 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011730 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011731 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011732 if (DEBUG_BROADCAST) {
11733 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011734 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011735 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011736 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011737 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011738 queue.enqueueOrderedBroadcastLocked(r);
11739 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011741 }
11742
Dianne Hackborna4972e92012-03-14 10:38:05 -070011743 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011744 }
11745
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011746 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011747 // Refuse possible leaked file descriptors
11748 if (intent != null && intent.hasFileDescriptors() == true) {
11749 throw new IllegalArgumentException("File descriptors passed in Intent");
11750 }
11751
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011752 int flags = intent.getFlags();
11753
11754 if (!mProcessesReady) {
11755 // if the caller really truly claims to know what they're doing, go
11756 // ahead and allow the broadcast without launching any receivers
11757 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11758 intent = new Intent(intent);
11759 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11760 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11761 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11762 + " before boot completion");
11763 throw new IllegalStateException("Cannot broadcast before boot completed");
11764 }
11765 }
11766
11767 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11768 throw new IllegalArgumentException(
11769 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11770 }
11771
11772 return intent;
11773 }
11774
11775 public final int broadcastIntent(IApplicationThread caller,
11776 Intent intent, String resolvedType, IIntentReceiver resultTo,
11777 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011778 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011779 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011780 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011781 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011783 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11784 final int callingPid = Binder.getCallingPid();
11785 final int callingUid = Binder.getCallingUid();
11786 final long origId = Binder.clearCallingIdentity();
11787 int res = broadcastIntentLocked(callerApp,
11788 callerApp != null ? callerApp.info.packageName : null,
11789 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011790 resultCode, resultData, map, requiredPermission, serialized, sticky,
11791 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011792 Binder.restoreCallingIdentity(origId);
11793 return res;
11794 }
11795 }
11796
11797 int broadcastIntentInPackage(String packageName, int uid,
11798 Intent intent, String resolvedType, IIntentReceiver resultTo,
11799 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011800 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011801 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011802 intent = verifyBroadcastLocked(intent);
11803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011804 final long origId = Binder.clearCallingIdentity();
11805 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11806 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011807 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011808 Binder.restoreCallingIdentity(origId);
11809 return res;
11810 }
11811 }
11812
Amith Yamasani742a6712011-05-04 14:49:28 -070011813 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011814 // Refuse possible leaked file descriptors
11815 if (intent != null && intent.hasFileDescriptors() == true) {
11816 throw new IllegalArgumentException("File descriptors passed in Intent");
11817 }
11818
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011819 userId = handleIncomingUserLocked(Binder.getCallingPid(),
11820 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011822 synchronized(this) {
11823 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11824 != PackageManager.PERMISSION_GRANTED) {
11825 String msg = "Permission Denial: unbroadcastIntent() from pid="
11826 + Binder.getCallingPid()
11827 + ", uid=" + Binder.getCallingUid()
11828 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011829 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011830 throw new SecurityException(msg);
11831 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011832 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11833 if (stickies != null) {
11834 ArrayList<Intent> list = stickies.get(intent.getAction());
11835 if (list != null) {
11836 int N = list.size();
11837 int i;
11838 for (i=0; i<N; i++) {
11839 if (intent.filterEquals(list.get(i))) {
11840 list.remove(i);
11841 break;
11842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011843 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011844 if (list.size() <= 0) {
11845 stickies.remove(intent.getAction());
11846 }
11847 }
11848 if (stickies.size() <= 0) {
11849 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011850 }
11851 }
11852 }
11853 }
11854
11855 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11856 String resultData, Bundle resultExtras, boolean resultAbort,
11857 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011858 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11859 if (r == null) {
11860 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011861 return false;
11862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011863
Christopher Tatef46723b2012-01-26 14:19:24 -080011864 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11865 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011866 }
11867
11868 public void finishReceiver(IBinder who, int resultCode, String resultData,
11869 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011870 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011871
11872 // Refuse possible leaked file descriptors
11873 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11874 throw new IllegalArgumentException("File descriptors passed in Bundle");
11875 }
11876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011877 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011878 try {
11879 boolean doNext = false;
11880 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011881
Christopher Tatef46723b2012-01-26 14:19:24 -080011882 synchronized(this) {
11883 r = broadcastRecordForReceiverLocked(who);
11884 if (r != null) {
11885 doNext = r.queue.finishReceiverLocked(r, resultCode,
11886 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011887 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011888 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011889
Christopher Tatef46723b2012-01-26 14:19:24 -080011890 if (doNext) {
11891 r.queue.processNextBroadcast(false);
11892 }
11893 trimApplications();
11894 } finally {
11895 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011899 // =========================================================
11900 // INSTRUMENTATION
11901 // =========================================================
11902
11903 public boolean startInstrumentation(ComponentName className,
11904 String profileFile, int flags, Bundle arguments,
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011905 IInstrumentationWatcher watcher, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011906 enforceNotIsolatedCaller("startInstrumentation");
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011907 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(),
11908 userId, false, true, "startInstrumentation", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011909 // Refuse possible leaked file descriptors
11910 if (arguments != null && arguments.hasFileDescriptors()) {
11911 throw new IllegalArgumentException("File descriptors passed in Bundle");
11912 }
11913
11914 synchronized(this) {
11915 InstrumentationInfo ii = null;
11916 ApplicationInfo ai = null;
11917 try {
11918 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011919 className, STOCK_PM_FLAGS);
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011920 ai = AppGlobals.getPackageManager().getApplicationInfo(
11921 ii.targetPackage, STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011922 } catch (PackageManager.NameNotFoundException e) {
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070011923 } catch (RemoteException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011924 }
11925 if (ii == null) {
11926 reportStartInstrumentationFailure(watcher, className,
11927 "Unable to find instrumentation info for: " + className);
11928 return false;
11929 }
11930 if (ai == null) {
11931 reportStartInstrumentationFailure(watcher, className,
11932 "Unable to find instrumentation target package: " + ii.targetPackage);
11933 return false;
11934 }
11935
11936 int match = mContext.getPackageManager().checkSignatures(
11937 ii.targetPackage, ii.packageName);
11938 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11939 String msg = "Permission Denial: starting instrumentation "
11940 + className + " from pid="
11941 + Binder.getCallingPid()
11942 + ", uid=" + Binder.getCallingPid()
11943 + " not allowed because package " + ii.packageName
11944 + " does not have a signature matching the target "
11945 + ii.targetPackage;
11946 reportStartInstrumentationFailure(watcher, className, msg);
11947 throw new SecurityException(msg);
11948 }
11949
11950 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070011951 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070011952 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011953 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011954 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011955 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011956 app.instrumentationProfileFile = profileFile;
11957 app.instrumentationArguments = arguments;
11958 app.instrumentationWatcher = watcher;
11959 app.instrumentationResultClass = className;
11960 Binder.restoreCallingIdentity(origId);
11961 }
11962
11963 return true;
11964 }
11965
11966 /**
11967 * Report errors that occur while attempting to start Instrumentation. Always writes the
11968 * error to the logs, but if somebody is watching, send the report there too. This enables
11969 * the "am" command to report errors with more information.
11970 *
11971 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11972 * @param cn The component name of the instrumentation.
11973 * @param report The error report.
11974 */
11975 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11976 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011977 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011978 try {
11979 if (watcher != null) {
11980 Bundle results = new Bundle();
11981 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11982 results.putString("Error", report);
11983 watcher.instrumentationStatus(cn, -1, results);
11984 }
11985 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011986 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011987 }
11988 }
11989
11990 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
11991 if (app.instrumentationWatcher != null) {
11992 try {
11993 // NOTE: IInstrumentationWatcher *must* be oneway here
11994 app.instrumentationWatcher.instrumentationFinished(
11995 app.instrumentationClass,
11996 resultCode,
11997 results);
11998 } catch (RemoteException e) {
11999 }
12000 }
12001 app.instrumentationWatcher = null;
12002 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070012003 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012004 app.instrumentationProfileFile = null;
12005 app.instrumentationArguments = null;
12006
Dianne Hackborn80a4af22012-08-27 19:18:31 -070012007 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012008 }
12009
12010 public void finishInstrumentation(IApplicationThread target,
12011 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012012 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012013 // Refuse possible leaked file descriptors
12014 if (results != null && results.hasFileDescriptors()) {
12015 throw new IllegalArgumentException("File descriptors passed in Intent");
12016 }
12017
12018 synchronized(this) {
12019 ProcessRecord app = getRecordForAppLocked(target);
12020 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012021 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012022 return;
12023 }
12024 final long origId = Binder.clearCallingIdentity();
12025 finishInstrumentationLocked(app, resultCode, results);
12026 Binder.restoreCallingIdentity(origId);
12027 }
12028 }
12029
12030 // =========================================================
12031 // CONFIGURATION
12032 // =========================================================
12033
12034 public ConfigurationInfo getDeviceConfigurationInfo() {
12035 ConfigurationInfo config = new ConfigurationInfo();
12036 synchronized (this) {
12037 config.reqTouchScreen = mConfiguration.touchscreen;
12038 config.reqKeyboardType = mConfiguration.keyboard;
12039 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012040 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
12041 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012042 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
12043 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070012044 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
12045 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012046 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
12047 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070012048 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012049 }
12050 return config;
12051 }
12052
12053 public Configuration getConfiguration() {
12054 Configuration ci;
12055 synchronized(this) {
12056 ci = new Configuration(mConfiguration);
12057 }
12058 return ci;
12059 }
12060
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012061 public void updatePersistentConfiguration(Configuration values) {
12062 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12063 "updateConfiguration()");
12064 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
12065 "updateConfiguration()");
12066 if (values == null) {
12067 throw new NullPointerException("Configuration must not be null");
12068 }
12069
12070 synchronized(this) {
12071 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080012072 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012073 Binder.restoreCallingIdentity(origId);
12074 }
12075 }
12076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012077 public void updateConfiguration(Configuration values) {
12078 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
12079 "updateConfiguration()");
12080
12081 synchronized(this) {
12082 if (values == null && mWindowManager != null) {
12083 // sentinel: fetch the current configuration from the window manager
12084 values = mWindowManager.computeNewConfiguration();
12085 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012086
12087 if (mWindowManager != null) {
12088 mProcessList.applyDisplaySize(mWindowManager);
12089 }
12090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012091 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012092 if (values != null) {
12093 Settings.System.clearConfiguration(values);
12094 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080012095 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012096 Binder.restoreCallingIdentity(origId);
12097 }
12098 }
12099
12100 /**
12101 * Do either or both things: (1) change the current configuration, and (2)
12102 * make sure the given activity is running with the (now) current
12103 * configuration. Returns true if the activity has been left running, or
12104 * false if <var>starting</var> is being destroyed to match the new
12105 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012106 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012107 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080012108 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080012109 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070012110 // do nothing if we are headless
12111 if (mHeadless) return true;
12112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012113 int changes = 0;
12114
12115 boolean kept = true;
12116
12117 if (values != null) {
12118 Configuration newConfig = new Configuration(mConfiguration);
12119 changes = newConfig.updateFrom(values);
12120 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012121 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012122 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012123 }
12124
Doug Zongker2bec3d42009-12-04 12:52:44 -080012125 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012126
Dianne Hackborn813075a62011-11-14 17:45:19 -080012127 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012128 saveLocaleLocked(values.locale,
12129 !values.locale.equals(mConfiguration.locale),
12130 values.userSetLocale);
12131 }
12132
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012133 mConfigurationSeq++;
12134 if (mConfigurationSeq <= 0) {
12135 mConfigurationSeq = 1;
12136 }
12137 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012138 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012139 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012140
12141 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012142
12143 // TODO: If our config changes, should we auto dismiss any currently
12144 // showing dialogs?
12145 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012146
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012147 AttributeCache ac = AttributeCache.instance();
12148 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012149 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012151
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012152 // Make sure all resources in our process are updated
12153 // right now, so that anyone who is going to retrieve
12154 // resource values after we return will be sure to get
12155 // the new ones. This is especially important during
12156 // boot, where the first config change needs to guarantee
12157 // all resources have that config before following boot
12158 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012159 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012160
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012161 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012162 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012163 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012164 mHandler.sendMessage(msg);
12165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012166
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012167 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12168 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012169 try {
12170 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012171 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012172 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012173 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012174 }
12175 } catch (Exception e) {
12176 }
12177 }
12178 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012179 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12180 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012181 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012182 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012183 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12184 broadcastIntentLocked(null, null,
12185 new Intent(Intent.ACTION_LOCALE_CHANGED),
12186 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012187 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012189 }
12190 }
12191
12192 if (changes != 0 && starting == null) {
12193 // If the configuration changed, and the caller is not already
12194 // in the process of starting an activity, then find the top
12195 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012196 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012197 }
12198
12199 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012200 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012201 // And we need to make sure at this point that all other activities
12202 // are made visible with the correct configuration.
12203 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012204 }
12205
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012206 if (values != null && mWindowManager != null) {
12207 mWindowManager.setNewConfiguration(mConfiguration);
12208 }
12209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012210 return kept;
12211 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012212
12213 /**
12214 * Decide based on the configuration whether we should shouw the ANR,
12215 * crash, etc dialogs. The idea is that if there is no affordnace to
12216 * press the on-screen buttons, we shouldn't show the dialog.
12217 *
12218 * A thought: SystemUI might also want to get told about this, the Power
12219 * dialog / global actions also might want different behaviors.
12220 */
12221 private static final boolean shouldShowDialogs(Configuration config) {
12222 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12223 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012225
12226 /**
12227 * Save the locale. You must be inside a synchronized (this) block.
12228 */
12229 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12230 if(isDiff) {
12231 SystemProperties.set("user.language", l.getLanguage());
12232 SystemProperties.set("user.region", l.getCountry());
12233 }
12234
12235 if(isPersist) {
12236 SystemProperties.set("persist.sys.language", l.getLanguage());
12237 SystemProperties.set("persist.sys.country", l.getCountry());
12238 SystemProperties.set("persist.sys.localevar", l.getVariant());
12239 }
12240 }
12241
Adam Powelldd8fab22012-03-22 17:47:27 -070012242 @Override
12243 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12244 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012245 return srec != null && srec.task.affinity != null &&
12246 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012247 }
12248
12249 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12250 Intent resultData) {
12251 ComponentName dest = destIntent.getComponent();
12252
12253 synchronized (this) {
12254 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012255 if (srec == null) {
12256 return false;
12257 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012258 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12259 final int start = history.indexOf(srec);
12260 if (start < 0) {
12261 // Current activity is not in history stack; do nothing.
12262 return false;
12263 }
12264 int finishTo = start - 1;
12265 ActivityRecord parent = null;
12266 boolean foundParentInTask = false;
12267 if (dest != null) {
12268 TaskRecord tr = srec.task;
12269 for (int i = start - 1; i >= 0; i--) {
12270 ActivityRecord r = history.get(i);
12271 if (tr != r.task) {
12272 // Couldn't find parent in the same task; stop at the one above this.
12273 // (Root of current task; in-app "home" behavior)
12274 // Always at least finish the current activity.
12275 finishTo = Math.min(start - 1, i + 1);
12276 parent = history.get(finishTo);
12277 break;
12278 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12279 r.info.name.equals(dest.getClassName())) {
12280 finishTo = i;
12281 parent = r;
12282 foundParentInTask = true;
12283 break;
12284 }
12285 }
12286 }
12287
12288 if (mController != null) {
12289 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12290 if (next != null) {
12291 // ask watcher if this is allowed
12292 boolean resumeOK = true;
12293 try {
12294 resumeOK = mController.activityResuming(next.packageName);
12295 } catch (RemoteException e) {
12296 mController = null;
12297 }
12298
12299 if (!resumeOK) {
12300 return false;
12301 }
12302 }
12303 }
12304 final long origId = Binder.clearCallingIdentity();
12305 for (int i = start; i > finishTo; i--) {
12306 ActivityRecord r = history.get(i);
12307 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
12308 "navigate-up");
12309 // Only return the supplied result for the first activity finished
12310 resultCode = Activity.RESULT_CANCELED;
12311 resultData = null;
12312 }
12313
12314 if (parent != null && foundParentInTask) {
12315 final int parentLaunchMode = parent.info.launchMode;
12316 final int destIntentFlags = destIntent.getFlags();
12317 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12318 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12319 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12320 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012321 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012322 } else {
12323 try {
12324 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012325 destIntent.getComponent(), 0, UserHandle.getCallingUserId());
Adam Powelldd8fab22012-03-22 17:47:27 -070012326 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12327 null, aInfo, parent.appToken, null,
12328 0, -1, parent.launchedFromUid, 0, null, true, null);
12329 foundParentInTask = res == ActivityManager.START_SUCCESS;
12330 } catch (RemoteException e) {
12331 foundParentInTask = false;
12332 }
12333 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
12334 resultData, "navigate-up");
12335 }
12336 }
12337 Binder.restoreCallingIdentity(origId);
12338 return foundParentInTask;
12339 }
12340 }
12341
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012342 public int getLaunchedFromUid(IBinder activityToken) {
12343 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12344 if (srec == null) {
12345 return -1;
12346 }
12347 return srec.launchedFromUid;
12348 }
12349
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012350 // =========================================================
12351 // LIFETIME MANAGEMENT
12352 // =========================================================
12353
Christopher Tatef46723b2012-01-26 14:19:24 -080012354 // Returns which broadcast queue the app is the current [or imminent] receiver
12355 // on, or 'null' if the app is not an active broadcast recipient.
12356 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12357 BroadcastRecord r = app.curReceiver;
12358 if (r != null) {
12359 return r.queue;
12360 }
12361
12362 // It's not the current receiver, but it might be starting up to become one
12363 synchronized (this) {
12364 for (BroadcastQueue queue : mBroadcastQueues) {
12365 r = queue.mPendingBroadcast;
12366 if (r != null && r.curApp == app) {
12367 // found it; report which queue it's in
12368 return queue;
12369 }
12370 }
12371 }
12372
12373 return null;
12374 }
12375
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012376 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012377 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012378 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012379 // This adjustment has already been computed. If we are calling
12380 // from the top, we may have already computed our adjustment with
12381 // an earlier hidden adjustment that isn't really for us... if
12382 // so, use the new hidden adjustment.
12383 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012384 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
12385 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012386 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012387 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012388 }
12389
12390 if (app.thread == null) {
12391 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012392 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012393 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012394 }
12395
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012396 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12397 app.adjSource = null;
12398 app.adjTarget = null;
12399 app.empty = false;
12400 app.hidden = false;
12401
12402 final int activitiesSize = app.activities.size();
12403
Dianne Hackborn7d608422011-08-07 16:24:18 -070012404 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012405 // The max adjustment doesn't allow this app to be anything
12406 // below foreground, so it is not worth doing work for it.
12407 app.adjType = "fixed";
12408 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012409 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012410 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012411 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012412 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012413 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012414 // System process can do UI, and when they do we want to have
12415 // them trim their memory after the user leaves the UI. To
12416 // facilitate this, here we need to determine whether or not it
12417 // is currently showing UI.
12418 app.systemNoUi = true;
12419 if (app == TOP_APP) {
12420 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012421 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012422 } else if (activitiesSize > 0) {
12423 for (int j = 0; j < activitiesSize; j++) {
12424 final ActivityRecord r = app.activities.get(j);
12425 if (r.visible) {
12426 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012427 }
12428 if (r.app == app) {
12429 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012430 }
12431 }
12432 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012433 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012434 }
12435
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012436 app.keeping = false;
12437 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012438 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012439
The Android Open Source Project4df24232009-03-05 14:34:35 -080012440 // Determine the importance of the process, starting with most
12441 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012442 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012443 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012444 boolean foregroundActivities = false;
12445 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012446 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012447 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012448 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012449 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012450 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012451 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012452 foregroundActivities = true;
12453 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012454 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012455 } else if (app.instrumentationClass != null) {
12456 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012457 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012458 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012459 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012460 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012461 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012462 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012463 // counts as being in the foreground for OOM killer purposes.
12464 // It's placed in a sched group based on the nature of the
12465 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012466 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012467 schedGroup = (queue == mFgBroadcastQueue)
12468 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012469 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012470 } else if (app.executingServices.size() > 0) {
12471 // An app that is currently executing a service callback also
12472 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012473 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012474 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012475 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012476 } else {
12477 // Assume process is hidden (has activities); we will correct
12478 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012479 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012480 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012481 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012482 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012483 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012484
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012485 boolean hasStoppingActivities = false;
12486
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012487 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012488 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012489 for (int j = 0; j < activitiesSize; j++) {
12490 final ActivityRecord r = app.activities.get(j);
12491 if (r.visible) {
12492 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012493 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12494 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012495 app.adjType = "visible";
12496 }
12497 schedGroup = Process.THREAD_GROUP_DEFAULT;
12498 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012499 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012500 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012501 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012502 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012503 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12504 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012505 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012506 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012507 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012508 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012509 } else if (r.state == ActivityState.STOPPING) {
12510 // We will apply the actual adjustment later, because
12511 // we want to allow this process to immediately go through
12512 // any memory trimming that is in effect.
12513 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012514 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012515 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012516 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012517 if (r.app == app) {
12518 app.hasActivities = true;
12519 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012520 }
12521 }
12522
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012523 if (adj == hiddenAdj && !app.hasActivities) {
12524 // Whoops, this process is completely empty as far as we know
12525 // at this point.
12526 adj = emptyAdj;
12527 app.empty = true;
12528 app.adjType = "bg-empty";
12529 }
12530
Dianne Hackborn7d608422011-08-07 16:24:18 -070012531 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012532 if (app.foregroundServices) {
12533 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012534 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012535 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012536 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012537 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012538 } else if (app.forcingToForeground != null) {
12539 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012540 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012541 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012542 app.adjType = "force-foreground";
12543 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012544 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012545 }
12546 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012547
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012548 if (app.foregroundServices) {
12549 interesting = true;
12550 }
12551
Dianne Hackborn7d608422011-08-07 16:24:18 -070012552 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012553 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012554 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012555 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012556 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012557 app.adjType = "heavy";
12558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012559
Dianne Hackborn7d608422011-08-07 16:24:18 -070012560 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012561 // This process is hosting what we currently consider to be the
12562 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012563 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012564 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012565 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012566 app.adjType = "home";
12567 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012568
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012569 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12570 && app.activities.size() > 0) {
12571 // This was the previous process that showed UI to the user.
12572 // We want to try to keep it around more aggressively, to give
12573 // a good experience around switching between two apps.
12574 adj = ProcessList.PREVIOUS_APP_ADJ;
12575 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12576 app.hidden = false;
12577 app.adjType = "previous";
12578 }
12579
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012580 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12581 + " reason=" + app.adjType);
12582
The Android Open Source Project4df24232009-03-05 14:34:35 -080012583 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012584 // there are applications dependent on our services or providers, but
12585 // this gives us a baseline and makes sure we don't get into an
12586 // infinite recursion.
12587 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012588 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012589
Christopher Tate6fa95972009-06-05 18:43:55 -070012590 if (mBackupTarget != null && app == mBackupTarget.app) {
12591 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012592 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012593 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012594 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012595 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012596 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012597 }
12598 }
12599
Dianne Hackborn7d608422011-08-07 16:24:18 -070012600 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012601 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012602 final long now = SystemClock.uptimeMillis();
12603 // This process is more important if the top activity is
12604 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012605 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012606 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012607 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012608 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012609 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012610 // If this process has shown some UI, let it immediately
12611 // go to the LRU list because it may be pretty heavy with
12612 // UI stuff. We'll tag it with a label just to help
12613 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012614 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012615 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012616 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012617 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012618 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012619 // This service has seen some activity within
12620 // recent memory, so we will keep its process ahead
12621 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012622 if (adj > ProcessList.SERVICE_ADJ) {
12623 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012624 app.adjType = "started-services";
12625 app.hidden = false;
12626 }
12627 }
12628 // If we have let the service slide into the background
12629 // state, still have some text describing what it is doing
12630 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012631 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012632 app.adjType = "started-bg-services";
12633 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012634 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012635 // Don't kill this process because it is doing work; it
12636 // has said it is doing work.
12637 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012638 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012639 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012640 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012641 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012642 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012643 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012644 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012645 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012646 // XXX should compute this based on the max of
12647 // all connected clients.
12648 ConnectionRecord cr = clist.get(i);
12649 if (cr.binding.client == app) {
12650 // Binding to ourself is not interesting.
12651 continue;
12652 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012653 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012654 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012655 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012656 int myHiddenAdj = hiddenAdj;
12657 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012658 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012659 myHiddenAdj = client.hiddenAdj;
12660 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012661 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012662 }
12663 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012664 int myEmptyAdj = emptyAdj;
12665 if (myEmptyAdj > client.emptyAdj) {
12666 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12667 myEmptyAdj = client.emptyAdj;
12668 } else {
12669 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12670 }
12671 }
12672 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12673 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012674 String adjType = null;
12675 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12676 // Not doing bind OOM management, so treat
12677 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012678 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012679 // If this process has shown some UI, let it immediately
12680 // go to the LRU list because it may be pretty heavy with
12681 // UI stuff. We'll tag it with a label just to help
12682 // debug and understand what is going on.
12683 if (adj > clientAdj) {
12684 adjType = "bound-bg-ui-services";
12685 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012686 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012687 clientAdj = adj;
12688 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012689 if (now >= (s.lastActivity
12690 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012691 // This service has not seen activity within
12692 // recent memory, so allow it to drop to the
12693 // LRU list if there is no other reason to keep
12694 // it around. We'll also tag it with a label just
12695 // to help debug and undertand what is going on.
12696 if (adj > clientAdj) {
12697 adjType = "bound-bg-services";
12698 }
12699 clientAdj = adj;
12700 }
12701 }
12702 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012703 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012704 // If this process has recently shown UI, and
12705 // the process that is binding to it is less
12706 // important than being visible, then we don't
12707 // care about the binding as much as we care
12708 // about letting this process get into the LRU
12709 // list to be killed and restarted if needed for
12710 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012711 if (app.hasShownUi && app != mHomeProcess
12712 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012713 adjType = "bound-bg-ui-services";
12714 } else {
12715 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12716 |Context.BIND_IMPORTANT)) != 0) {
12717 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012718 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12719 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12720 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12721 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12722 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012723 adj = clientAdj;
12724 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012725 app.pendingUiClean = true;
12726 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12727 adj = ProcessList.VISIBLE_APP_ADJ;
12728 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012729 }
12730 if (!client.hidden) {
12731 app.hidden = false;
12732 }
12733 if (client.keeping) {
12734 app.keeping = true;
12735 }
12736 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012737 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012738 }
12739 if (adjType != null) {
12740 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012741 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12742 .REASON_SERVICE_IN_USE;
12743 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012744 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012745 app.adjTarget = s.name;
12746 }
12747 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12748 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12749 schedGroup = Process.THREAD_GROUP_DEFAULT;
12750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012751 }
12752 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012753 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12754 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012755 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012756 (a.visible || a.state == ActivityState.RESUMED
12757 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012758 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012759 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12760 schedGroup = Process.THREAD_GROUP_DEFAULT;
12761 }
12762 app.hidden = false;
12763 app.adjType = "service";
12764 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12765 .REASON_SERVICE_IN_USE;
12766 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012767 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012768 app.adjTarget = s.name;
12769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012771 }
12772 }
12773 }
12774 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012775
Dianne Hackborn287952c2010-09-22 22:34:31 -070012776 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012777 // would like to avoid killing it unless it would prevent the current
12778 // application from running. By default we put the process in
12779 // with the rest of the background processes; as we scan through
12780 // its services we may bump it up from there.
12781 if (adj > hiddenAdj) {
12782 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012783 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012784 app.adjType = "bg-services";
12785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012786 }
12787
Dianne Hackborn7d608422011-08-07 16:24:18 -070012788 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012789 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012790 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012791 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012792 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012793 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012794 for (int i = cpr.connections.size()-1;
12795 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12796 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12797 i--) {
12798 ContentProviderConnection conn = cpr.connections.get(i);
12799 ProcessRecord client = conn.client;
12800 if (client == app) {
12801 // Being our own client is not interesting.
12802 continue;
12803 }
12804 int myHiddenAdj = hiddenAdj;
12805 if (myHiddenAdj > client.hiddenAdj) {
12806 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12807 myHiddenAdj = client.hiddenAdj;
12808 } else {
12809 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012810 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012811 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012812 int myEmptyAdj = emptyAdj;
12813 if (myEmptyAdj > client.emptyAdj) {
12814 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12815 myEmptyAdj = client.emptyAdj;
12816 } else {
12817 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12818 }
12819 }
12820 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12821 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012822 if (adj > clientAdj) {
12823 if (app.hasShownUi && app != mHomeProcess
12824 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12825 app.adjType = "bg-ui-provider";
12826 } else {
12827 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12828 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12829 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012830 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012831 if (!client.hidden) {
12832 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012833 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012834 if (client.keeping) {
12835 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012836 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012837 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12838 .REASON_PROVIDER_IN_USE;
12839 app.adjSource = client;
12840 app.adjSourceOom = clientAdj;
12841 app.adjTarget = cpr.name;
12842 }
12843 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12844 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012845 }
12846 }
12847 // If the provider has external (non-framework) process
12848 // dependencies, ensure that its adjustment is at least
12849 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012850 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012851 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12852 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012853 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012854 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012855 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012856 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012857 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012858 }
12859 }
12860 }
12861 }
12862
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012863 if (adj == ProcessList.SERVICE_ADJ) {
12864 if (doingAll) {
12865 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12866 mNewNumServiceProcs++;
12867 }
12868 if (app.serviceb) {
12869 adj = ProcessList.SERVICE_B_ADJ;
12870 }
12871 } else {
12872 app.serviceb = false;
12873 }
12874
12875 app.nonStoppingAdj = adj;
12876
12877 if (hasStoppingActivities) {
12878 // Only upgrade adjustment.
12879 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12880 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12881 app.adjType = "stopping";
12882 }
12883 }
12884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012885 app.curRawAdj = adj;
12886
Joe Onorato8a9b2202010-02-26 18:56:32 -080012887 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012888 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12889 if (adj > app.maxAdj) {
12890 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012891 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012892 schedGroup = Process.THREAD_GROUP_DEFAULT;
12893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012894 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012895 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012896 app.keeping = true;
12897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012898
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012899 if (app.hasAboveClient) {
12900 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12901 // then we need to drop its adjustment to be lower than the service's
12902 // in order to honor the request. We want to drop it by one adjustment
12903 // level... but there is special meaning applied to various levels so
12904 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012905 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012906 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012907 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12908 adj = ProcessList.VISIBLE_APP_ADJ;
12909 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12910 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12911 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12912 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012913 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012914 adj++;
12915 }
12916 }
12917
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012918 int importance = app.memImportance;
12919 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12920 app.curAdj = adj;
12921 app.curSchedGroup = schedGroup;
12922 if (!interesting) {
12923 // For this reporting, if there is not something explicitly
12924 // interesting in this process then we will push it to the
12925 // background importance.
12926 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12927 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12928 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12929 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12930 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12931 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12932 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12933 } else if (adj >= ProcessList.SERVICE_ADJ) {
12934 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12935 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12936 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12937 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12938 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
12939 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
12940 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
12941 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
12942 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
12943 } else {
12944 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
12945 }
12946 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012947
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012948 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
12949 if (foregroundActivities != app.foregroundActivities) {
12950 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
12951 }
12952 if (changes != 0) {
12953 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
12954 app.memImportance = importance;
12955 app.foregroundActivities = foregroundActivities;
12956 int i = mPendingProcessChanges.size()-1;
12957 ProcessChangeItem item = null;
12958 while (i >= 0) {
12959 item = mPendingProcessChanges.get(i);
12960 if (item.pid == app.pid) {
12961 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
12962 break;
12963 }
12964 i--;
12965 }
12966 if (i < 0) {
12967 // No existing item in pending changes; need a new one.
12968 final int NA = mAvailProcessChanges.size();
12969 if (NA > 0) {
12970 item = mAvailProcessChanges.remove(NA-1);
12971 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
12972 } else {
12973 item = new ProcessChangeItem();
12974 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
12975 }
12976 item.changes = 0;
12977 item.pid = app.pid;
12978 item.uid = app.info.uid;
12979 if (mPendingProcessChanges.size() == 0) {
12980 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
12981 "*** Enqueueing dispatch processes changed!");
12982 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
12983 }
12984 mPendingProcessChanges.add(item);
12985 }
12986 item.changes |= changes;
12987 item.importance = importance;
12988 item.foregroundActivities = foregroundActivities;
12989 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
12990 + Integer.toHexString(System.identityHashCode(item))
12991 + " " + app.toShortString() + ": changes=" + item.changes
12992 + " importance=" + item.importance
12993 + " foreground=" + item.foregroundActivities
12994 + " type=" + app.adjType + " source=" + app.adjSource
12995 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012996 }
12997
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012998 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012999 }
13000
13001 /**
13002 * Ask a given process to GC right now.
13003 */
13004 final void performAppGcLocked(ProcessRecord app) {
13005 try {
13006 app.lastRequestedGc = SystemClock.uptimeMillis();
13007 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013008 if (app.reportLowMemory) {
13009 app.reportLowMemory = false;
13010 app.thread.scheduleLowMemory();
13011 } else {
13012 app.thread.processInBackground();
13013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013014 }
13015 } catch (Exception e) {
13016 // whatever.
13017 }
13018 }
13019
13020 /**
13021 * Returns true if things are idle enough to perform GCs.
13022 */
Josh Bartel7f208742010-02-25 11:01:44 -060013023 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080013024 boolean processingBroadcasts = false;
13025 for (BroadcastQueue q : mBroadcastQueues) {
13026 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
13027 processingBroadcasts = true;
13028 }
13029 }
13030 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013031 && (mSleeping || (mMainStack.mResumedActivity != null &&
13032 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013033 }
13034
13035 /**
13036 * Perform GCs on all processes that are waiting for it, but only
13037 * if things are idle.
13038 */
13039 final void performAppGcsLocked() {
13040 final int N = mProcessesToGc.size();
13041 if (N <= 0) {
13042 return;
13043 }
Josh Bartel7f208742010-02-25 11:01:44 -060013044 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013045 while (mProcessesToGc.size() > 0) {
13046 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013047 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013048 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
13049 <= SystemClock.uptimeMillis()) {
13050 // To avoid spamming the system, we will GC processes one
13051 // at a time, waiting a few seconds between each.
13052 performAppGcLocked(proc);
13053 scheduleAppGcsLocked();
13054 return;
13055 } else {
13056 // It hasn't been long enough since we last GCed this
13057 // process... put it in the list to wait for its time.
13058 addProcessToGcListLocked(proc);
13059 break;
13060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013061 }
13062 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013063
13064 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013065 }
13066 }
13067
13068 /**
13069 * If all looks good, perform GCs on all processes waiting for them.
13070 */
13071 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060013072 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013073 performAppGcsLocked();
13074 return;
13075 }
13076 // Still not idle, wait some more.
13077 scheduleAppGcsLocked();
13078 }
13079
13080 /**
13081 * Schedule the execution of all pending app GCs.
13082 */
13083 final void scheduleAppGcsLocked() {
13084 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013085
13086 if (mProcessesToGc.size() > 0) {
13087 // Schedule a GC for the time to the next process.
13088 ProcessRecord proc = mProcessesToGc.get(0);
13089 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
13090
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013091 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013092 long now = SystemClock.uptimeMillis();
13093 if (when < (now+GC_TIMEOUT)) {
13094 when = now + GC_TIMEOUT;
13095 }
13096 mHandler.sendMessageAtTime(msg, when);
13097 }
13098 }
13099
13100 /**
13101 * Add a process to the array of processes waiting to be GCed. Keeps the
13102 * list in sorted order by the last GC time. The process can't already be
13103 * on the list.
13104 */
13105 final void addProcessToGcListLocked(ProcessRecord proc) {
13106 boolean added = false;
13107 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
13108 if (mProcessesToGc.get(i).lastRequestedGc <
13109 proc.lastRequestedGc) {
13110 added = true;
13111 mProcessesToGc.add(i+1, proc);
13112 break;
13113 }
13114 }
13115 if (!added) {
13116 mProcessesToGc.add(0, proc);
13117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013118 }
13119
13120 /**
13121 * Set up to ask a process to GC itself. This will either do it
13122 * immediately, or put it on the list of processes to gc the next
13123 * time things are idle.
13124 */
13125 final void scheduleAppGcLocked(ProcessRecord app) {
13126 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013127 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013128 return;
13129 }
13130 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013131 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013132 scheduleAppGcsLocked();
13133 }
13134 }
13135
Dianne Hackborn287952c2010-09-22 22:34:31 -070013136 final void checkExcessivePowerUsageLocked(boolean doKills) {
13137 updateCpuStatsNow();
13138
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013139 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013140 boolean doWakeKills = doKills;
13141 boolean doCpuKills = doKills;
13142 if (mLastPowerCheckRealtime == 0) {
13143 doWakeKills = false;
13144 }
13145 if (mLastPowerCheckUptime == 0) {
13146 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013147 }
13148 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013149 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013150 }
13151 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013152 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13153 final long curUptime = SystemClock.uptimeMillis();
13154 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13155 mLastPowerCheckRealtime = curRealtime;
13156 mLastPowerCheckUptime = curUptime;
13157 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13158 doWakeKills = false;
13159 }
13160 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13161 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013162 }
13163 int i = mLruProcesses.size();
13164 while (i > 0) {
13165 i--;
13166 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013167 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013168 long wtime;
13169 synchronized (stats) {
13170 wtime = stats.getProcessWakeTime(app.info.uid,
13171 app.pid, curRealtime);
13172 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013173 long wtimeUsed = wtime - app.lastWakeTime;
13174 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13175 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013176 StringBuilder sb = new StringBuilder(128);
13177 sb.append("Wake for ");
13178 app.toShortString(sb);
13179 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013180 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013181 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013182 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013183 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013184 sb.append((wtimeUsed*100)/realtimeSince);
13185 sb.append("%)");
13186 Slog.i(TAG, sb.toString());
13187 sb.setLength(0);
13188 sb.append("CPU for ");
13189 app.toShortString(sb);
13190 sb.append(": over ");
13191 TimeUtils.formatDuration(uptimeSince, sb);
13192 sb.append(" used ");
13193 TimeUtils.formatDuration(cputimeUsed, sb);
13194 sb.append(" (");
13195 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013196 sb.append("%)");
13197 Slog.i(TAG, sb.toString());
13198 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013199 // If a process has held a wake lock for more
13200 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013201 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013202 if (doWakeKills && realtimeSince > 0
13203 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13204 synchronized (stats) {
13205 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13206 realtimeSince, wtimeUsed);
13207 }
13208 Slog.w(TAG, "Excessive wake lock in " + app.processName
13209 + " (pid " + app.pid + "): held " + wtimeUsed
13210 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013211 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13212 app.processName, app.setAdj, "excessive wake lock");
13213 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013214 } else if (doCpuKills && uptimeSince > 0
13215 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13216 synchronized (stats) {
13217 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13218 uptimeSince, cputimeUsed);
13219 }
13220 Slog.w(TAG, "Excessive CPU in " + app.processName
13221 + " (pid " + app.pid + "): used " + cputimeUsed
13222 + " during " + uptimeSince);
13223 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13224 app.processName, app.setAdj, "excessive cpu");
13225 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013226 } else {
13227 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013228 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013229 }
13230 }
13231 }
13232 }
13233
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013234 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
13235 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013236 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013237 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013238
13239 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013240 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013241 }
13242
Dianne Hackborn287952c2010-09-22 22:34:31 -070013243 final boolean wasKeeping = app.keeping;
13244
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013245 boolean success = true;
13246
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013247 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013248
Jeff Brown10e89712011-07-08 18:52:57 -070013249 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013250 if (wasKeeping && !app.keeping) {
13251 // This app is no longer something we want to keep. Note
13252 // its current wake lock time to later know to kill it if
13253 // it is not behaving well.
13254 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13255 synchronized (stats) {
13256 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13257 app.pid, SystemClock.elapsedRealtime());
13258 }
13259 app.lastCpuTime = app.curCpuTime;
13260 }
13261
13262 app.setRawAdj = app.curRawAdj;
13263 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013264
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013265 if (app.curAdj != app.setAdj) {
13266 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013267 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013268 TAG, "Set " + app.pid + " " + app.processName +
13269 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013270 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013271 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013272 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013273 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013274 }
13275 }
13276 if (app.setSchedGroup != app.curSchedGroup) {
13277 app.setSchedGroup = app.curSchedGroup;
13278 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13279 "Setting process group of " + app.processName
13280 + " to " + app.curSchedGroup);
13281 if (app.waitingToKill != null &&
13282 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13283 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13284 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13285 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013286 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013287 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013288 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013289 } else {
13290 if (true) {
13291 long oldId = Binder.clearCallingIdentity();
13292 try {
13293 Process.setProcessGroup(app.pid, app.curSchedGroup);
13294 } catch (Exception e) {
13295 Slog.w(TAG, "Failed setting process group of " + app.pid
13296 + " to " + app.curSchedGroup);
13297 e.printStackTrace();
13298 } finally {
13299 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013300 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013301 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013302 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013303 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013304 app.thread.setSchedulingGroup(app.curSchedGroup);
13305 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013306 }
13307 }
13308 }
13309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013310 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013311 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013312 }
13313
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013314 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013315 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013316 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013317 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013318 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013319 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013320 }
13321 }
13322 return resumedActivity;
13323 }
13324
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013325 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013326 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013327 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13328 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013329 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13330 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013331
13332 mAdjSeq++;
13333
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013334 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
13335 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013336 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13337 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013338 if (nowHidden != wasHidden) {
13339 // Changed to/from hidden state, so apps after it in the LRU
13340 // list may also be changed.
13341 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013342 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013343 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013344 }
13345
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013346 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013347 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013348 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13349
13350 if (false) {
13351 RuntimeException e = new RuntimeException();
13352 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013353 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013354 }
13355
13356 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013357 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013358
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013359 // Let's determine how many processes we have running vs.
13360 // how many slots we have for background processes; we may want
13361 // to put multiple processes in a slot of there are enough of
13362 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013363 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13364 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
13365 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
13366 if (emptyFactor < 1) emptyFactor = 1;
13367 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13368 if (hiddenFactor < 1) hiddenFactor = 1;
13369 int stepHidden = 0;
13370 int stepEmpty = 0;
13371 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
13372 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013373 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013374 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013375 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013376
13377 mNumNonHiddenProcs = 0;
13378 mNumHiddenProcs = 0;
13379
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013380 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013381 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013382 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013383 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013384 int nextHiddenAdj = curHiddenAdj+1;
13385 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13386 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013387 while (i > 0) {
13388 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013389 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013390 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013391 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013392 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013393 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13394 // This process was assigned as a hidden process... step the
13395 // hidden level.
13396 mNumHiddenProcs++;
13397 if (curHiddenAdj != nextHiddenAdj) {
13398 stepHidden++;
13399 if (stepHidden >= hiddenFactor) {
13400 stepHidden = 0;
13401 curHiddenAdj = nextHiddenAdj;
13402 nextHiddenAdj += 2;
13403 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13404 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13405 }
13406 }
13407 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013408 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013409 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013410 Slog.i(TAG, "No longer want " + app.processName
13411 + " (pid " + app.pid + "): hidden #" + numHidden);
13412 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13413 app.processName, app.setAdj, "too many background");
13414 app.killedBackground = true;
13415 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013416 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013417 } else {
13418 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13419 // This process was assigned as an empty process... step the
13420 // empty level.
13421 if (curEmptyAdj != nextEmptyAdj) {
13422 stepEmpty++;
13423 if (stepEmpty >= emptyFactor) {
13424 stepEmpty = 0;
13425 curEmptyAdj = nextEmptyAdj;
13426 nextEmptyAdj += 2;
13427 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13428 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13429 }
13430 }
13431 }
13432 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13433 mNumNonHiddenProcs++;
13434 }
13435 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13436 numEmpty++;
13437 if (numEmpty > emptyProcessLimit) {
13438 Slog.i(TAG, "No longer want " + app.processName
13439 + " (pid " + app.pid + "): empty #" + numEmpty);
13440 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13441 app.processName, app.setAdj, "too many background");
13442 app.killedBackground = true;
13443 Process.killProcessQuiet(app.pid);
13444 }
13445 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013446 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013447 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013448 // If this is an isolated process, and there are no
13449 // services running in it, then the process is no longer
13450 // needed. We agressively kill these because we can by
13451 // definition not re-use the same process again, and it is
13452 // good to avoid having whatever code was running in them
13453 // left sitting around after no longer needed.
13454 Slog.i(TAG, "Isolated process " + app.processName
13455 + " (pid " + app.pid + ") no longer needed");
13456 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13457 app.processName, app.setAdj, "isolated not needed");
13458 app.killedBackground = true;
13459 Process.killProcessQuiet(app.pid);
13460 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013461 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13462 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13463 && !app.killedBackground) {
13464 numTrimming++;
13465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013466 }
13467 }
13468
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013469 mNumServiceProcs = mNewNumServiceProcs;
13470
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013471 // Now determine the memory trimming level of background processes.
13472 // Unfortunately we need to start at the back of the list to do this
13473 // properly. We only do this if the number of background apps we
13474 // are managing to keep around is less than half the maximum we desire;
13475 // if we are keeping a good number around, we'll let them use whatever
13476 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013477 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13478 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13479 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013480 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013481 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013482 int minFactor = 2;
13483 if (mHomeProcess != null) minFactor++;
13484 if (mPreviousProcess != null) minFactor++;
13485 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013486 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013487 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013488 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013489 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013490 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013491 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13492 } else {
13493 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13494 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013495 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013496 for (i=0; i<N; i++) {
13497 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013498 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13499 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013500 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013501 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13502 try {
13503 app.thread.scheduleTrimMemory(curLevel);
13504 } catch (RemoteException e) {
13505 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013506 if (false) {
13507 // For now we won't do this; our memory trimming seems
13508 // to be good enough at this point that destroying
13509 // activities causes more harm than good.
13510 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13511 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013512 // Need to do this on its own message because the stack may not
13513 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013514 // For these apps we will also finish their activities
13515 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013516 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013517 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013518 }
13519 }
13520 app.trimMemoryLevel = curLevel;
13521 step++;
13522 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013523 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013524 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013525 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13526 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013527 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013528 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13529 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013530 break;
13531 }
13532 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013533 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013534 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013535 && app.thread != null) {
13536 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013537 app.thread.scheduleTrimMemory(
13538 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013539 } catch (RemoteException e) {
13540 }
13541 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013542 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013543 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013544 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013545 && app.pendingUiClean) {
13546 // If this application is now in the background and it
13547 // had done UI, then give it the special trim level to
13548 // have it free UI resources.
13549 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13550 if (app.trimMemoryLevel < level && app.thread != null) {
13551 try {
13552 app.thread.scheduleTrimMemory(level);
13553 } catch (RemoteException e) {
13554 }
13555 }
13556 app.pendingUiClean = false;
13557 }
13558 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013559 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013560 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013561 } catch (RemoteException e) {
13562 }
13563 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013564 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013565 }
13566 }
13567 } else {
13568 final int N = mLruProcesses.size();
13569 for (i=0; i<N; i++) {
13570 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013571 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013572 && app.pendingUiClean) {
13573 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13574 && app.thread != null) {
13575 try {
13576 app.thread.scheduleTrimMemory(
13577 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13578 } catch (RemoteException e) {
13579 }
13580 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013581 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013582 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013583 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013584 }
13585 }
13586
13587 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013588 // Need to do this on its own message because the stack may not
13589 // be in a consistent state at this point.
13590 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013592 }
13593
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013594 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013595 synchronized (this) {
13596 int i;
13597
13598 // First remove any unused application processes whose package
13599 // has been removed.
13600 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13601 final ProcessRecord app = mRemovedProcesses.get(i);
13602 if (app.activities.size() == 0
13603 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013604 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013605 TAG, "Exiting empty application process "
13606 + app.processName + " ("
13607 + (app.thread != null ? app.thread.asBinder() : null)
13608 + ")\n");
13609 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013610 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13611 app.processName, app.setAdj, "empty");
13612 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013613 } else {
13614 try {
13615 app.thread.scheduleExit();
13616 } catch (Exception e) {
13617 // Ignore exceptions.
13618 }
13619 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013620 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013621 mRemovedProcesses.remove(i);
13622
13623 if (app.persistent) {
13624 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013625 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013626 }
13627 }
13628 }
13629 }
13630
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013631 // Now update the oom adj for all processes.
13632 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013633 }
13634 }
13635
13636 /** This method sends the specified signal to each of the persistent apps */
13637 public void signalPersistentProcesses(int sig) throws RemoteException {
13638 if (sig != Process.SIGNAL_USR1) {
13639 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13640 }
13641
13642 synchronized (this) {
13643 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13644 != PackageManager.PERMISSION_GRANTED) {
13645 throw new SecurityException("Requires permission "
13646 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13647 }
13648
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013649 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13650 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013651 if (r.thread != null && r.persistent) {
13652 Process.sendSignal(r.pid, sig);
13653 }
13654 }
13655 }
13656 }
13657
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013658 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13659 if (proc == null || proc == mProfileProc) {
13660 proc = mProfileProc;
13661 path = mProfileFile;
13662 profileType = mProfileType;
13663 clearProfilerLocked();
13664 }
13665 if (proc == null) {
13666 return;
13667 }
13668 try {
13669 proc.thread.profilerControl(false, path, null, profileType);
13670 } catch (RemoteException e) {
13671 throw new IllegalStateException("Process disappeared");
13672 }
13673 }
13674
13675 private void clearProfilerLocked() {
13676 if (mProfileFd != null) {
13677 try {
13678 mProfileFd.close();
13679 } catch (IOException e) {
13680 }
13681 }
13682 mProfileApp = null;
13683 mProfileProc = null;
13684 mProfileFile = null;
13685 mProfileType = 0;
13686 mAutoStopProfiler = false;
13687 }
13688
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013689 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013690 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013691
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013692 try {
13693 synchronized (this) {
13694 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13695 // its own permission.
13696 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13697 != PackageManager.PERMISSION_GRANTED) {
13698 throw new SecurityException("Requires permission "
13699 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013700 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013701
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013702 if (start && fd == null) {
13703 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013704 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013705
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013706 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013707 if (process != null) {
13708 try {
13709 int pid = Integer.parseInt(process);
13710 synchronized (mPidsSelfLocked) {
13711 proc = mPidsSelfLocked.get(pid);
13712 }
13713 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013714 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013715
13716 if (proc == null) {
13717 HashMap<String, SparseArray<ProcessRecord>> all
13718 = mProcessNames.getMap();
13719 SparseArray<ProcessRecord> procs = all.get(process);
13720 if (procs != null && procs.size() > 0) {
13721 proc = procs.valueAt(0);
13722 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013723 }
13724 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013725
13726 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013727 throw new IllegalArgumentException("Unknown process: " + process);
13728 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013729
13730 if (start) {
13731 stopProfilerLocked(null, null, 0);
13732 setProfileApp(proc.info, proc.processName, path, fd, false);
13733 mProfileProc = proc;
13734 mProfileType = profileType;
13735 try {
13736 fd = fd.dup();
13737 } catch (IOException e) {
13738 fd = null;
13739 }
13740 proc.thread.profilerControl(start, path, fd, profileType);
13741 fd = null;
13742 mProfileFd = null;
13743 } else {
13744 stopProfilerLocked(proc, path, profileType);
13745 if (fd != null) {
13746 try {
13747 fd.close();
13748 } catch (IOException e) {
13749 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013750 }
13751 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013752
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013753 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013754 }
13755 } catch (RemoteException e) {
13756 throw new IllegalStateException("Process disappeared");
13757 } finally {
13758 if (fd != null) {
13759 try {
13760 fd.close();
13761 } catch (IOException e) {
13762 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013763 }
13764 }
13765 }
Andy McFadden824c5102010-07-09 16:26:57 -070013766
13767 public boolean dumpHeap(String process, boolean managed,
13768 String path, ParcelFileDescriptor fd) throws RemoteException {
13769
13770 try {
13771 synchronized (this) {
13772 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13773 // its own permission (same as profileControl).
13774 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13775 != PackageManager.PERMISSION_GRANTED) {
13776 throw new SecurityException("Requires permission "
13777 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13778 }
13779
13780 if (fd == null) {
13781 throw new IllegalArgumentException("null fd");
13782 }
13783
13784 ProcessRecord proc = null;
13785 try {
13786 int pid = Integer.parseInt(process);
13787 synchronized (mPidsSelfLocked) {
13788 proc = mPidsSelfLocked.get(pid);
13789 }
13790 } catch (NumberFormatException e) {
13791 }
13792
13793 if (proc == null) {
13794 HashMap<String, SparseArray<ProcessRecord>> all
13795 = mProcessNames.getMap();
13796 SparseArray<ProcessRecord> procs = all.get(process);
13797 if (procs != null && procs.size() > 0) {
13798 proc = procs.valueAt(0);
13799 }
13800 }
13801
13802 if (proc == null || proc.thread == null) {
13803 throw new IllegalArgumentException("Unknown process: " + process);
13804 }
13805
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013806 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13807 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013808 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13809 throw new SecurityException("Process not debuggable: " + proc);
13810 }
13811 }
13812
13813 proc.thread.dumpHeap(managed, path, fd);
13814 fd = null;
13815 return true;
13816 }
13817 } catch (RemoteException e) {
13818 throw new IllegalStateException("Process disappeared");
13819 } finally {
13820 if (fd != null) {
13821 try {
13822 fd.close();
13823 } catch (IOException e) {
13824 }
13825 }
13826 }
13827 }
13828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013829 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13830 public void monitor() {
13831 synchronized (this) { }
13832 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013833
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013834 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013835 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13836 ProcessRecord processRecord = mLruProcesses.get(i);
13837 try {
13838 if (processRecord.thread != null) {
13839 processRecord.thread.setCoreSettings(settings);
13840 }
13841 } catch (RemoteException re) {
13842 /* ignore */
13843 }
13844 }
13845 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013846
13847 // Multi-user methods
13848
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013849 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070013850 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013851 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13852 != PackageManager.PERMISSION_GRANTED) {
13853 String msg = "Permission Denial: switchUser() from pid="
13854 + Binder.getCallingPid()
13855 + ", uid=" + Binder.getCallingUid()
13856 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13857 Slog.w(TAG, msg);
13858 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013859 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013860 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013861 if (mCurrentUserId == userId) {
13862 return true;
13863 }
13864
13865 // If the user we are switching to is not currently started, then
13866 // we need to start it now.
13867 if (mStartedUsers.get(userId) == null) {
13868 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Amith Yamasani742a6712011-05-04 14:49:28 -070013869 }
13870
13871 mCurrentUserId = userId;
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070013872 Integer userIdInt = Integer.valueOf(userId);
13873 mUserLru.remove(userIdInt);
13874 mUserLru.add(userIdInt);
Amith Yamasani742a6712011-05-04 14:49:28 -070013875 boolean haveActivities = mMainStack.switchUser(userId);
13876 if (!haveActivities) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013877 startHomeActivityLocked(userId, mStartedUsers.get(userId));
Amith Yamasani742a6712011-05-04 14:49:28 -070013878 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013879 }
Amith Yamasani13593602012-03-22 16:16:17 -070013880
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013881 long ident = Binder.clearCallingIdentity();
13882 try {
13883 // Inform of user switch
13884 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
13885 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070013886 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
13887 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013888 } finally {
13889 Binder.restoreCallingIdentity(ident);
13890 }
Amith Yamasani13593602012-03-22 16:16:17 -070013891
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013892 return true;
13893 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013894
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013895 void finishUserSwitch(UserStartedState uss) {
13896 synchronized (this) {
13897 if (uss.mState == UserStartedState.STATE_BOOTING
13898 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
13899 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070013900 final int userId = uss.mHandle.getIdentifier();
13901 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
13902 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
13903 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013904 null, null, 0, null, null,
13905 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070013906 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013907 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013908 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013909 }
13910
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013911 @Override
13912 public int stopUser(final int userId, final IStopUserCallback callback) {
13913 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13914 != PackageManager.PERMISSION_GRANTED) {
13915 String msg = "Permission Denial: switchUser() from pid="
13916 + Binder.getCallingPid()
13917 + ", uid=" + Binder.getCallingUid()
13918 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13919 Slog.w(TAG, msg);
13920 throw new SecurityException(msg);
13921 }
13922 if (userId <= 0) {
13923 throw new IllegalArgumentException("Can't stop primary user " + userId);
13924 }
Amith Yamasani13593602012-03-22 16:16:17 -070013925 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013926 if (mCurrentUserId == userId) {
13927 return ActivityManager.USER_OP_IS_CURRENT;
13928 }
13929
13930 final UserStartedState uss = mStartedUsers.get(userId);
13931 if (uss == null) {
13932 // User is not started, nothing to do... but we do need to
13933 // callback if requested.
13934 if (callback != null) {
13935 mHandler.post(new Runnable() {
13936 @Override
13937 public void run() {
13938 try {
13939 callback.userStopped(userId);
13940 } catch (RemoteException e) {
13941 }
13942 }
13943 });
13944 }
13945 return ActivityManager.USER_OP_SUCCESS;
13946 }
13947
13948 if (callback != null) {
13949 uss.mStopCallbacks.add(callback);
13950 }
13951
13952 if (uss.mState != UserStartedState.STATE_STOPPING) {
13953 uss.mState = UserStartedState.STATE_STOPPING;
13954
13955 long ident = Binder.clearCallingIdentity();
13956 try {
13957 // Inform of user switch
13958 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
13959 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
13960 @Override
13961 public void performReceive(Intent intent, int resultCode, String data,
Dianne Hackborn20e80982012-08-31 19:00:44 -070013962 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013963 finishUserStop(uss);
13964 }
13965 };
13966 broadcastIntentLocked(null, null, intent,
13967 null, resultReceiver, 0, null, null, null,
13968 true, false, MY_PID, Process.SYSTEM_UID, userId);
13969 } finally {
13970 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070013971 }
13972 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013973 }
Amith Yamasani13593602012-03-22 16:16:17 -070013974
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013975 return ActivityManager.USER_OP_SUCCESS;
13976 }
13977
13978 void finishUserStop(UserStartedState uss) {
13979 final int userId = uss.mHandle.getIdentifier();
13980 boolean stopped;
13981 ArrayList<IStopUserCallback> callbacks;
13982 synchronized (this) {
13983 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
13984 if (uss.mState != UserStartedState.STATE_STOPPING
13985 || mStartedUsers.get(userId) != uss) {
13986 stopped = false;
13987 } else {
13988 stopped = true;
13989 // User can no longer run.
13990 mStartedUsers.remove(userId);
13991
13992 // Clean up all state and processes associated with the user.
13993 // Kill all the processes for the user.
13994 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070013995 }
13996 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013997
13998 for (int i=0; i<callbacks.size(); i++) {
13999 try {
14000 if (stopped) callbacks.get(i).userStopped(userId);
14001 else callbacks.get(i).userStopAborted(userId);
14002 } catch (RemoteException e) {
14003 }
14004 }
14005 }
14006
14007 @Override
14008 public UserInfo getCurrentUser() {
14009 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
14010 != PackageManager.PERMISSION_GRANTED) {
14011 String msg = "Permission Denial: getCurrentUser() from pid="
14012 + Binder.getCallingPid()
14013 + ", uid=" + Binder.getCallingUid()
14014 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
14015 Slog.w(TAG, msg);
14016 throw new SecurityException(msg);
14017 }
14018 synchronized (this) {
14019 return getUserManager().getUserInfo(mCurrentUserId);
14020 }
Amith Yamasani13593602012-03-22 16:16:17 -070014021 }
14022
Dianne Hackborn5e03e2c2012-09-06 14:21:19 -070014023 @Override
14024 public boolean isUserRunning(int userId) {
14025 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS)
14026 != PackageManager.PERMISSION_GRANTED) {
14027 String msg = "Permission Denial: isUserRunning() from pid="
14028 + Binder.getCallingPid()
14029 + ", uid=" + Binder.getCallingUid()
14030 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS;
14031 Slog.w(TAG, msg);
14032 throw new SecurityException(msg);
14033 }
14034 synchronized (this) {
14035 UserStartedState state = mStartedUsers.get(userId);
14036 return state != null && state.mState != UserStartedState.STATE_STOPPING;
14037 }
14038 }
14039
Amith Yamasani742a6712011-05-04 14:49:28 -070014040 private boolean userExists(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -070014041 UserInfo user = getUserManager().getUserInfo(userId);
14042 return user != null;
14043 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014044
Amith Yamasani258848d2012-08-10 17:06:33 -070014045 UserManager getUserManager() {
14046 if (mUserManager == null) {
14047 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
14048 }
14049 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070014050 }
14051
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014052 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014053 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080014054
14055 throw new SecurityException("Caller uid=" + uid
14056 + " is not privileged to communicate with user=" + userId);
14057 }
Amith Yamasani742a6712011-05-04 14:49:28 -070014058
14059 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014060 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070014061 }
14062
Dianne Hackborn599db5c2012-08-03 19:28:48 -070014063 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080014064 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070014065 ApplicationInfo newInfo = new ApplicationInfo(info);
14066 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070014067 newInfo.dataDir = USER_DATA_DIR + userId + "/"
14068 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070014069 return newInfo;
14070 }
14071
14072 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070014073 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070014074 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070014075 return aInfo;
14076 }
14077
14078 ActivityInfo info = new ActivityInfo(aInfo);
14079 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
14080 return info;
14081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080014082}