blob: 590e9d9addc56e799cc4dfce8b639865a7eb2357 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006-2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey110a6b62012-03-12 11:12:41 -070019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Dianne Hackborn860755f2010-06-03 18:47:52 -070021import com.android.internal.R;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import com.android.internal.os.BatteryStatsImpl;
Dianne Hackborn45ce8642011-07-14 16:10:16 -070023import com.android.internal.os.ProcessStats;
Dianne Hackbornde7faf62009-06-30 13:27:30 -070024import com.android.server.AttributeCache;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025import com.android.server.IntentResolver;
26import com.android.server.ProcessMap;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.SystemServer;
28import com.android.server.Watchdog;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import com.android.server.am.ActivityStack.ActivityState;
Dianne Hackborna924dc0d2011-02-17 14:22:17 -080030import com.android.server.wm.WindowManagerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031
Dianne Hackborndd71fc82009-12-16 19:24:32 -080032import dalvik.system.Zygote;
33
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.app.Activity;
35import android.app.ActivityManager;
36import android.app.ActivityManagerNative;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -070037import android.app.ActivityOptions;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.app.ActivityThread;
39import android.app.AlertDialog;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070040import android.app.AppGlobals;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020041import android.app.ApplicationErrorReport;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.app.Dialog;
Dianne Hackbornb06ea702009-07-13 13:07:51 -070043import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.app.IApplicationThread;
45import android.app.IInstrumentationWatcher;
Dianne Hackborn860755f2010-06-03 18:47:52 -070046import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070047import android.app.IProcessObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.app.IServiceConnection;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070049import android.app.IStopUserCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.app.IThumbnailReceiver;
51import android.app.Instrumentation;
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070052import android.app.Notification;
Dianne Hackborn860755f2010-06-03 18:47:52 -070053import android.app.NotificationManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.app.PendingIntent;
Christopher Tate45281862010-03-05 15:46:30 -080055import android.app.backup.IBackupManager;
Jacek Surazskif5b9c722009-05-18 12:09:59 +020056import android.content.ActivityNotFoundException;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080057import android.content.BroadcastReceiver;
Dianne Hackborn21c241e2012-03-08 13:57:23 -080058import android.content.ClipData;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070059import android.content.ComponentCallbacks2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.ComponentName;
Jeff Sharkey110a6b62012-03-12 11:12:41 -070061import android.content.ContentProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.content.ContentResolver;
63import android.content.Context;
Christian Mehlmauer7664e202010-07-20 08:46:17 +020064import android.content.DialogInterface;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070065import android.content.IContentProvider;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070066import android.content.IIntentReceiver;
67import android.content.IIntentSender;
Adam Powelldd8fab22012-03-22 17:47:27 -070068import android.content.Intent;
69import android.content.IntentFilter;
Dianne Hackbornfa82f222009-09-17 15:14:12 -070070import android.content.IntentSender;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.content.pm.ActivityInfo;
72import android.content.pm.ApplicationInfo;
73import android.content.pm.ConfigurationInfo;
74import android.content.pm.IPackageDataObserver;
75import android.content.pm.IPackageManager;
76import android.content.pm.InstrumentationInfo;
Dan Egnor66c40e72010-01-26 16:23:11 -080077import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.content.pm.PackageManager;
Amith Yamasani258848d2012-08-10 17:06:33 -070079import android.content.pm.UserInfo;
Adam Powelldd8fab22012-03-22 17:47:27 -070080import android.content.pm.PackageManager.NameNotFoundException;
Dianne Hackborn2af632f2009-07-08 14:56:37 -070081import android.content.pm.PathPermission;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.content.pm.ProviderInfo;
83import android.content.pm.ResolveInfo;
84import android.content.pm.ServiceInfo;
Dianne Hackborne2515ee2011-04-27 18:52:56 -040085import android.content.res.CompatibilityInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.content.res.Configuration;
87import android.graphics.Bitmap;
Robert Greenwalt434203a2010-10-11 16:00:27 -070088import android.net.Proxy;
89import android.net.ProxyProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.net.Uri;
91import android.os.Binder;
Dan Egnor60d87622009-12-16 16:32:58 -080092import android.os.Build;
Dan Egnor42471dd2010-01-07 17:25:22 -080093import android.os.Bundle;
Dianne Hackborn3025ef32009-08-31 21:31:47 -070094import android.os.Debug;
Dan Egnor60d87622009-12-16 16:32:58 -080095import android.os.DropBoxManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.os.Environment;
Dan Egnor42471dd2010-01-07 17:25:22 -080097import android.os.FileObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.FileUtils;
99import android.os.Handler;
100import android.os.IBinder;
101import android.os.IPermissionController;
102import android.os.Looper;
103import android.os.Message;
104import android.os.Parcel;
105import android.os.ParcelFileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import android.os.Process;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700107import android.os.RemoteCallbackList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import android.os.RemoteException;
rpcraigec7ed14c2012-07-25 13:10:37 -0400109import android.os.SELinux;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import android.os.ServiceManager;
Brad Fitzpatrick46d42382010-06-11 13:57:58 -0700111import android.os.StrictMode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import android.os.SystemClock;
113import android.os.SystemProperties;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700114import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700115import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116import android.provider.Settings;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700117import android.text.format.Time;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import android.util.EventLog;
Joe Onorato5d3bea62010-03-01 13:44:29 -0800119import android.util.Log;
Adam Powelldd8fab22012-03-22 17:47:27 -0700120import android.util.Pair;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121import android.util.PrintWriterPrinter;
Adam Powelldd8fab22012-03-22 17:47:27 -0700122import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import android.util.SparseArray;
Amith Yamasani742a6712011-05-04 14:49:28 -0700124import android.util.SparseIntArray;
Dianne Hackborn1ebccf52010-08-15 13:04:34 -0700125import android.util.TimeUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126import android.view.Gravity;
127import android.view.LayoutInflater;
128import android.view.View;
129import android.view.WindowManager;
130import android.view.WindowManagerPolicy;
131
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700132import java.io.BufferedInputStream;
133import java.io.BufferedOutputStream;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700134import java.io.BufferedReader;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700135import java.io.DataInputStream;
136import java.io.DataOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.File;
138import java.io.FileDescriptor;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700139import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140import java.io.FileNotFoundException;
Dianne Hackborncef65ee2010-09-30 18:27:22 -0700141import java.io.FileOutputStream;
Jacek Surazskif5b9c722009-05-18 12:09:59 +0200142import java.io.IOException;
Dan Egnora455d192010-03-12 08:52:28 -0800143import java.io.InputStreamReader;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144import java.io.PrintWriter;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700145import java.io.StringWriter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800146import java.lang.ref.WeakReference;
147import java.util.ArrayList;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700148import java.util.Collections;
149import java.util.Comparator;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150import java.util.HashMap;
151import java.util.HashSet;
152import java.util.Iterator;
153import java.util.List;
154import java.util.Locale;
155import java.util.Map;
Amith Yamasani13593602012-03-22 16:16:17 -0700156import java.util.Map.Entry;
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -0700157import java.util.Set;
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700158import java.util.concurrent.atomic.AtomicBoolean;
159import java.util.concurrent.atomic.AtomicLong;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700161public final class ActivityManagerService extends ActivityManagerNative
162 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
Amith Yamasani742a6712011-05-04 14:49:28 -0700163 private static final String USER_DATA_DIR = "/data/user/";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164 static final String TAG = "ActivityManager";
Amith Yamasani742a6712011-05-04 14:49:28 -0700165 static final String TAG_MU = "ActivityManagerServiceMU";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166 static final boolean DEBUG = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400167 static final boolean localLOGV = DEBUG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 static final boolean DEBUG_SWITCH = localLOGV || false;
169 static final boolean DEBUG_TASKS = localLOGV || false;
170 static final boolean DEBUG_PAUSE = localLOGV || false;
171 static final boolean DEBUG_OOM_ADJ = localLOGV || false;
172 static final boolean DEBUG_TRANSITION = localLOGV || false;
173 static final boolean DEBUG_BROADCAST = localLOGV || false;
Christopher Tatef46723b2012-01-26 14:19:24 -0800174 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false;
Dianne Hackborn82f3f002009-06-16 18:49:05 -0700175 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 static final boolean DEBUG_SERVICE = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700177 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 static final boolean DEBUG_VISBILITY = localLOGV || false;
179 static final boolean DEBUG_PROCESSES = localLOGV || false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700180 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false;
Dianne Hackborna1e989b2009-09-01 19:54:29 -0700181 static final boolean DEBUG_PROVIDER = localLOGV || false;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800182 static final boolean DEBUG_URI_PERMISSION = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 static final boolean DEBUG_USER_LEAVING = localLOGV || false;
The Android Open Source Project10592532009-03-18 17:39:46 -0700184 static final boolean DEBUG_RESULTS = localLOGV || false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700185 static final boolean DEBUG_BACKUP = localLOGV || false;
Dianne Hackborndc6b6352009-09-30 14:20:09 -0700186 static final boolean DEBUG_CONFIGURATION = localLOGV || false;
Dianne Hackborn287952c2010-09-22 22:34:31 -0700187 static final boolean DEBUG_POWER = localLOGV || false;
188 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700189 static final boolean DEBUG_MU = localLOGV || false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 static final boolean VALIDATE_TOKENS = false;
191 static final boolean SHOW_ACTIVITY_START_TIME = true;
192
193 // Control over CPU and battery monitoring.
194 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes.
195 static final boolean MONITOR_CPU_USAGE = true;
196 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds.
197 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample.
198 static final boolean MONITOR_THREAD_CPU_USAGE = false;
199
Dianne Hackborn1655be42009-05-08 14:29:01 -0700200 // The flags that are set for all calls we make to the package manager.
Dianne Hackborn11b822d2009-07-21 20:03:02 -0700201 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES;
Dianne Hackborn1655be42009-05-08 14:29:01 -0700202
Dianne Hackbornf02e57b2011-03-01 22:21:04 -0800203 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700205 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE);
206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 // Maximum number of recent tasks that we can remember.
208 static final int MAX_RECENT_TASKS = 20;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700209
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700210 // Amount of time after a call to stopAppSwitches() during which we will
211 // prevent further untrusted switches from happening.
212 static final long APP_SWITCH_DELAY_TIME = 5*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
214 // How long we wait for a launched process to attach to the activity manager
215 // before we decide it's never going to come up for real.
216 static final int PROC_START_TIMEOUT = 10*1000;
217
Jeff Brown3f9dd282011-07-08 20:02:19 -0700218 // How long we wait for a launched process to attach to the activity manager
219 // before we decide it's never going to come up for real, when the process was
220 // started with a wrapper for instrumentation (such as Valgrind) because it
221 // could take much longer than usual.
222 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000;
223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 // How long to wait after going idle before forcing apps to GC.
225 static final int GC_TIMEOUT = 5*1000;
226
Dianne Hackbornfd12af42009-08-27 00:44:33 -0700227 // The minimum amount of time between successive GC requests for a process.
228 static final int GC_MIN_INTERVAL = 60*1000;
229
Dianne Hackborn287952c2010-09-22 22:34:31 -0700230 // The rate at which we check for apps using excessive power -- 15 mins.
231 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000;
232
233 // The minimum sample duration we will allow before deciding we have
234 // enough data on wake locks to start killing things.
235 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
236
237 // The minimum sample duration we will allow before deciding we have
238 // enough data on CPU usage to start killing things.
239 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 // How long we allow a receiver to run before giving up on it.
Christopher Tatef46723b2012-01-26 14:19:24 -0800242 static final int BROADCAST_FG_TIMEOUT = 10*1000;
243 static final int BROADCAST_BG_TIMEOUT = 60*1000;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 // How long we wait until we timeout on key dispatching.
246 static final int KEY_DISPATCHING_TIMEOUT = 5*1000;
247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // How long we wait until we timeout on key dispatching during instrumentation.
249 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000;
250
Dan Egnor42471dd2010-01-07 17:25:22 -0800251 static final int MY_PID = Process.myPid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252
253 static final String[] EMPTY_STRING_ARRAY = new String[0];
254
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700255 public ActivityStack mMainStack;
Mike Lockwood3a74bd32011-08-12 13:55:22 -0700256
257 private final boolean mHeadless;
258
Joe Onorato54a4a412011-11-02 20:50:08 -0700259 // Whether we should show our dialogs (ANR, crash, etc) or just perform their
260 // default actuion automatically. Important for devices without direct input
261 // devices.
262 private boolean mShowDialogs = true;
263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700265 * Description of a request to start a new activity, which has been held
266 * due to app switches being disabled.
267 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700268 static class PendingActivityLaunch {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700269 ActivityRecord r;
270 ActivityRecord sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -0700271 int startFlags;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700272 }
273
274 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches
275 = new ArrayList<PendingActivityLaunch>();
276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800278 BroadcastQueue mFgBroadcastQueue;
279 BroadcastQueue mBgBroadcastQueue;
Christopher Tatef46723b2012-01-26 14:19:24 -0800280 // Convenient for easy iteration over the queues. Foreground is first
281 // so that dispatch of foreground broadcasts gets precedence.
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800282 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2];
Christopher Tatef46723b2012-01-26 14:19:24 -0800283
284 BroadcastQueue broadcastQueueForIntent(Intent intent) {
285 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0;
286 if (DEBUG_BACKGROUND_BROADCAST) {
287 Slog.i(TAG, "Broadcast intent " + intent + " on "
288 + (isFg ? "foreground" : "background")
289 + " queue");
290 }
291 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue;
292 }
293
294 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) {
295 for (BroadcastQueue queue : mBroadcastQueues) {
296 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver);
297 if (r != null) {
298 return r;
299 }
300 }
301 return null;
302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303
304 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 * Activity we have told the window manager to have key focus.
306 */
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -0700307 ActivityRecord mFocusedActivity = null;
Dianne Hackbornbfe319e2009-09-21 00:34:05 -0700308 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309 * List of intents that were used to start the most recent tasks.
310 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700311 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312
313 /**
Dianne Hackborn7d608422011-08-07 16:24:18 -0700314 * Process management.
315 */
316 final ProcessList mProcessList = new ProcessList();
317
318 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800319 * All of the applications we currently have running organized by name.
320 * The keys are strings of the application package name (as
321 * returned by the package manager), and the keys are ApplicationRecord
322 * objects.
323 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700324 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325
326 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800327 * The currently running isolated processes.
328 */
329 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>();
330
331 /**
332 * Counter for assigning isolated process uids, to avoid frequently reusing the
333 * same ones.
334 */
335 int mNextIsolatedProcessUid = 0;
336
337 /**
Dianne Hackborn860755f2010-06-03 18:47:52 -0700338 * The currently running heavy-weight process, if any.
339 */
340 ProcessRecord mHeavyWeightProcess = null;
341
342 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 * The last time that various processes have crashed.
344 */
345 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>();
346
347 /**
348 * Set of applications that we consider to be bad, and will reject
349 * incoming broadcasts from (which the user has no control over).
350 * Processes are added to this set when they have crashed twice within
351 * a minimum amount of time; they are removed from it when they are
352 * later restarted (hopefully due to some user action). The value is the
353 * time it was added to the list.
354 */
355 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>();
356
357 /**
358 * All of the processes we currently have running organized by pid.
359 * The keys are the pid running the application.
360 *
361 * <p>NOTE: This object is protected by its own lock, NOT the global
362 * activity manager lock!
363 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700364 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365
366 /**
367 * All of the processes that have been forced to be foreground. The key
368 * is the pid of the caller who requested it (we hold a death
369 * link on it).
370 */
371 abstract class ForegroundToken implements IBinder.DeathRecipient {
372 int pid;
373 IBinder token;
374 }
375 final SparseArray<ForegroundToken> mForegroundProcesses
376 = new SparseArray<ForegroundToken>();
377
378 /**
379 * List of records for processes that someone had tried to start before the
380 * system was ready. We don't start them at that point, but ensure they
381 * are started by the time booting is complete.
382 */
383 final ArrayList<ProcessRecord> mProcessesOnHold
384 = new ArrayList<ProcessRecord>();
385
386 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800387 * List of persistent applications that are in the process
388 * of being started.
389 */
390 final ArrayList<ProcessRecord> mPersistentStartingProcesses
391 = new ArrayList<ProcessRecord>();
392
393 /**
394 * Processes that are being forcibly torn down.
395 */
396 final ArrayList<ProcessRecord> mRemovedProcesses
397 = new ArrayList<ProcessRecord>();
398
399 /**
400 * List of running applications, sorted by recent usage.
401 * The first entry in the list is the least recently used.
402 * It contains ApplicationRecord objects. This list does NOT include
403 * any persistent application records (since we never want to exit them).
404 */
Dianne Hackborndd71fc82009-12-16 19:24:32 -0800405 final ArrayList<ProcessRecord> mLruProcesses
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 = new ArrayList<ProcessRecord>();
407
408 /**
409 * List of processes that should gc as soon as things are idle.
410 */
411 final ArrayList<ProcessRecord> mProcessesToGc
412 = new ArrayList<ProcessRecord>();
413
414 /**
The Android Open Source Project4df24232009-03-05 14:34:35 -0800415 * This is the process holding what we currently consider to be
416 * the "home" activity.
417 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700418 ProcessRecord mHomeProcess;
The Android Open Source Project4df24232009-03-05 14:34:35 -0800419
420 /**
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700421 * This is the process holding the activity the user last visited that
422 * is in a different process from the one they are currently in.
423 */
424 ProcessRecord mPreviousProcess;
Dianne Hackborn50685602011-12-01 12:23:37 -0800425
426 /**
427 * The time at which the previous process was last visible.
428 */
429 long mPreviousProcessVisibleTime;
430
Dianne Hackbornf35fe232011-11-01 19:25:20 -0700431 /**
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700432 * Which uses have been started, so are allowed to run code.
433 */
434 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>();
435
436 /**
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400437 * Packages that the user has asked to have run in screen size
438 * compatibility mode instead of filling the screen.
439 */
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -0700440 final CompatModePackages mCompatModePackages;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400441
442 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 * Set of PendingResultRecord objects that are currently active.
444 */
445 final HashSet mPendingResultRecords = new HashSet();
446
447 /**
448 * Set of IntentSenderRecord objects that are currently active.
449 */
450 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords
451 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>();
452
453 /**
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -0800454 * Fingerprints (hashCode()) of stack traces that we've
Brad Fitzpatrick143666f2010-06-14 12:40:21 -0700455 * already logged DropBox entries for. Guarded by itself. If
456 * something (rogue user app) forces this over
457 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared.
458 */
459 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>();
460 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000;
461
462 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -0700463 * Strict Mode background batched logging state.
464 *
465 * The string buffer is guarded by itself, and its lock is also
466 * used to determine if another batched write is already
467 * in-flight.
468 */
469 private final StringBuilder mStrictModeBuffer = new StringBuilder();
470
471 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 * Keeps track of all IIntentReceivers that have been registered for
473 * broadcasts. Hash keys are the receiver IBinder, hash value is
474 * a ReceiverList.
475 */
476 final HashMap mRegisteredReceivers = new HashMap();
477
478 /**
479 * Resolver for broadcast intents to registered receivers.
480 * Holds BroadcastFilter (subclass of IntentFilter).
481 */
482 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver
483 = new IntentResolver<BroadcastFilter, BroadcastFilter>() {
484 @Override
485 protected boolean allowFilterResult(
486 BroadcastFilter filter, List<BroadcastFilter> dest) {
487 IBinder target = filter.receiverList.receiver.asBinder();
488 for (int i=dest.size()-1; i>=0; i--) {
489 if (dest.get(i).receiverList.receiver.asBinder() == target) {
490 return false;
491 }
492 }
493 return true;
494 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700495
496 @Override
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700497 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) {
498 if (userId == UserHandle.USER_ALL || userId == filter.owningUserId) {
499 return super.newResult(filter, match, userId);
500 }
501 return null;
502 }
503
504 @Override
Dianne Hackborn9ec6cdd2012-05-31 10:57:54 -0700505 protected BroadcastFilter[] newArray(int size) {
506 return new BroadcastFilter[size];
507 }
508
509 @Override
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700510 protected String packageForFilter(BroadcastFilter filter) {
511 return filter.packageName;
512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 };
514
515 /**
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700516 * State of all active sticky broadcasts per user. Keys are the action of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 * sticky Intent, values are an ArrayList of all broadcasted intents with
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700518 * that action (which should usually be one). The SparseArray is keyed
519 * by the user ID the sticky is for, and can include UserHandle.USER_ALL
520 * for stickies that are sent to all users.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800521 */
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700522 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts =
523 new SparseArray<HashMap<String, ArrayList<Intent>>>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700525 final ActiveServices mServices;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526
527 /**
Christopher Tate181fafa2009-05-14 11:12:14 -0700528 * Backup/restore process management
529 */
530 String mBackupAppName = null;
531 BackupRecord mBackupTarget = null;
532
533 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800534 * List of PendingThumbnailsRecord objects of clients who are still
535 * waiting to receive all of the thumbnails for a task.
536 */
537 final ArrayList mPendingThumbnails = new ArrayList();
538
539 /**
540 * List of HistoryRecord objects that have been finished and must
541 * still report back to a pending thumbnail receiver.
542 */
543 final ArrayList mCancelledThumbnails = new ArrayList();
544
Amith Yamasani742a6712011-05-04 14:49:28 -0700545 final ProviderMap mProviderMap = new ProviderMap();
546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 /**
548 * List of content providers who have clients waiting for them. The
549 * application is currently being launched and the provider will be
550 * removed from this list once it is published.
551 */
Dianne Hackborn860755f2010-06-03 18:47:52 -0700552 final ArrayList<ContentProviderRecord> mLaunchingProviders
553 = new ArrayList<ContentProviderRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800554
555 /**
556 * Global set of specific Uri permissions that have been granted.
557 */
558 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions
559 = new SparseArray<HashMap<Uri, UriPermission>>();
560
Svetoslav Ganov54d068e2011-03-02 12:58:40 -0800561 CoreSettingsObserver mCoreSettingsObserver;
562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 /**
564 * Thread-local storage used to carry caller permissions over through
565 * indirect content-provider access.
566 * @see #ActivityManagerService.openContentUri()
567 */
568 private class Identity {
569 public int pid;
570 public int uid;
571
572 Identity(int _pid, int _uid) {
573 pid = _pid;
574 uid = _uid;
575 }
576 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>();
579
580 /**
581 * All information we have collected about the runtime performance of
582 * any user id that can impact battery performance.
583 */
584 final BatteryStatsService mBatteryStatsService;
585
586 /**
587 * information about component usage
588 */
589 final UsageStatsService mUsageStatsService;
590
591 /**
592 * Current configuration information. HistoryRecord objects are given
593 * a reference to this object to indicate which configuration they are
594 * currently running in, so this object must be kept immutable.
595 */
596 Configuration mConfiguration = new Configuration();
597
598 /**
Dianne Hackborne36d6e22010-02-17 19:46:25 -0800599 * Current sequencing integer of the configuration, for skipping old
600 * configurations.
601 */
602 int mConfigurationSeq = 0;
603
604 /**
Jack Palevichb90d28c2009-07-22 15:35:24 -0700605 * Hardware-reported OpenGLES version.
606 */
607 final int GL_ES_VERSION;
608
609 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 * List of initialization arguments to pass to all processes when binding applications to them.
611 * For example, references to the commonly used services.
612 */
613 HashMap<String, IBinder> mAppBindArgs;
614
615 /**
Dianne Hackbornf210d6b2009-04-13 18:42:49 -0700616 * Temporary to avoid allocations. Protected by main lock.
617 */
618 final StringBuilder mStringBuilder = new StringBuilder(256);
619
620 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800621 * Used to control how we initialize the service.
622 */
623 boolean mStartRunning = false;
624 ComponentName mTopComponent;
625 String mTopAction;
626 String mTopData;
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700627 boolean mProcessesReady = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 boolean mSystemReady = false;
629 boolean mBooting = false;
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700630 boolean mWaitingUpdate = false;
631 boolean mDidUpdate = false;
Dianne Hackborn0d903a82010-09-07 23:51:03 -0700632 boolean mOnBattery = false;
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700633 boolean mLaunchWarningShown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634
635 Context mContext;
636
637 int mFactoryTest;
638
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -0700639 boolean mCheckedForSetup;
640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 /**
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700642 * The time at which we will allow normal application switches again,
643 * after a call to {@link #stopAppSwitches()}.
644 */
645 long mAppSwitchesAllowedTime;
646
647 /**
648 * This is set to true after the first switch after mAppSwitchesAllowedTime
649 * is set; any switches after that will clear the time.
650 */
651 boolean mDidAppSwitch;
652
653 /**
Dianne Hackborn287952c2010-09-22 22:34:31 -0700654 * Last time (in realtime) at which we checked for power usage.
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700655 */
Dianne Hackborn287952c2010-09-22 22:34:31 -0700656 long mLastPowerCheckRealtime;
657
658 /**
659 * Last time (in uptime) at which we checked for power usage.
660 */
661 long mLastPowerCheckUptime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700662
663 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800664 * Set while we are wanting to sleep, to prevent any
665 * activities from being started/resumed.
666 */
667 boolean mSleeping = false;
668
669 /**
Dianne Hackbornff5b1582012-04-12 17:24:07 -0700670 * State of external calls telling us if the device is asleep.
671 */
672 boolean mWentToSleep = false;
673
674 /**
675 * State of external call telling us if the lock screen is shown.
676 */
677 boolean mLockScreenShown = false;
678
679 /**
Dianne Hackborn55280a92009-05-07 15:53:46 -0700680 * Set if we are shutting down the system, similar to sleeping.
681 */
682 boolean mShuttingDown = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800683
684 /**
685 * Task identifier that activities are currently being started
686 * in. Incremented each time a new task is created.
687 * todo: Replace this with a TokenSpace class that generates non-repeating
688 * integers that won't wrap.
689 */
690 int mCurTask = 1;
691
692 /**
693 * Current sequence id for oom_adj computation traversal.
694 */
695 int mAdjSeq = 0;
696
697 /**
Dianne Hackborn906497c2010-05-10 15:57:38 -0700698 * Current sequence id for process LRU updating.
699 */
700 int mLruSeq = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701
702 /**
Dianne Hackbornee7621c2012-08-13 16:42:18 -0700703 * Keep track of the non-hidden/empty process we last found, to help
704 * determine how to distribute hidden/empty processes next time.
705 */
706 int mNumNonHiddenProcs = 0;
707
708 /**
709 * Keep track of the number of hidden procs, to balance oom adj
710 * distribution between those and empty procs.
711 */
712 int mNumHiddenProcs = 0;
713
714 /**
Dianne Hackborne02c88a2011-10-28 13:58:15 -0700715 * Keep track of the number of service processes we last found, to
716 * determine on the next iteration which should be B services.
717 */
718 int mNumServiceProcs = 0;
719 int mNewNumServiceProcs = 0;
720
721 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 * System monitoring: number of processes that died since the last
723 * N procs were started.
724 */
725 int[] mProcDeaths = new int[20];
726
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700727 /**
728 * This is set if we had to do a delayed dexopt of an app before launching
729 * it, to increasing the ANR timeouts in that case.
730 */
731 boolean mDidDexOpt;
732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 String mDebugApp = null;
734 boolean mWaitForDebugger = false;
735 boolean mDebugTransient = false;
736 String mOrigDebugApp = null;
737 boolean mOrigWaitForDebugger = false;
738 boolean mAlwaysFinishActivities = false;
Dianne Hackbornb06ea702009-07-13 13:07:51 -0700739 IActivityController mController = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700740 String mProfileApp = null;
741 ProcessRecord mProfileProc = null;
742 String mProfileFile;
743 ParcelFileDescriptor mProfileFd;
744 int mProfileType = 0;
745 boolean mAutoStopProfiler = false;
Siva Velusamy92a8b222012-03-09 16:24:04 -0800746 String mOpenGlTraceApp = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700748 static class ProcessChangeItem {
749 static final int CHANGE_ACTIVITIES = 1<<0;
750 static final int CHANGE_IMPORTANCE= 1<<1;
751 int changes;
752 int uid;
753 int pid;
754 int importance;
755 boolean foregroundActivities;
756 }
757
Jeff Sharkeya4620792011-05-20 15:29:23 -0700758 final RemoteCallbackList<IProcessObserver> mProcessObservers
759 = new RemoteCallbackList<IProcessObserver>();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700760 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5];
761
762 final ArrayList<ProcessChangeItem> mPendingProcessChanges
763 = new ArrayList<ProcessChangeItem>();
764 final ArrayList<ProcessChangeItem> mAvailProcessChanges
765 = new ArrayList<ProcessChangeItem>();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 /**
768 * Callback of last caller to {@link #requestPss}.
769 */
770 Runnable mRequestPssCallback;
771
772 /**
773 * Remaining processes for which we are waiting results from the last
774 * call to {@link #requestPss}.
775 */
776 final ArrayList<ProcessRecord> mRequestPssList
777 = new ArrayList<ProcessRecord>();
778
779 /**
780 * Runtime statistics collection thread. This object's lock is used to
781 * protect all related state.
782 */
783 final Thread mProcessStatsThread;
784
785 /**
786 * Used to collect process stats when showing not responding dialog.
787 * Protected by mProcessStatsThread.
788 */
789 final ProcessStats mProcessStats = new ProcessStats(
790 MONITOR_THREAD_CPU_USAGE);
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -0700791 final AtomicLong mLastCpuTime = new AtomicLong(0);
792 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true);
793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 long mLastWriteTime = 0;
795
796 /**
797 * Set to true after the system has finished booting.
798 */
799 boolean mBooted = false;
800
Dianne Hackborn7d608422011-08-07 16:24:18 -0700801 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700802 int mProcessLimitOverride = -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803
804 WindowManagerService mWindowManager;
805
806 static ActivityManagerService mSelf;
807 static ActivityThread mSystemThread;
808
Amith Yamasani258848d2012-08-10 17:06:33 -0700809 private int mCurrentUserId;
Amith Yamasani258848d2012-08-10 17:06:33 -0700810 private UserManager mUserManager;
811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 private final class AppDeathRecipient implements IBinder.DeathRecipient {
813 final ProcessRecord mApp;
814 final int mPid;
815 final IApplicationThread mAppThread;
816
817 AppDeathRecipient(ProcessRecord app, int pid,
818 IApplicationThread thread) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800819 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 TAG, "New death recipient " + this
821 + " for thread " + thread.asBinder());
822 mApp = app;
823 mPid = pid;
824 mAppThread = thread;
825 }
826
827 public void binderDied() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800828 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800829 TAG, "Death received in " + this
830 + " for thread " + mAppThread.asBinder());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 synchronized(ActivityManagerService.this) {
832 appDiedLocked(mApp, mPid, mAppThread);
833 }
834 }
835 }
836
837 static final int SHOW_ERROR_MSG = 1;
838 static final int SHOW_NOT_RESPONDING_MSG = 2;
839 static final int SHOW_FACTORY_ERROR_MSG = 3;
840 static final int UPDATE_CONFIGURATION_MSG = 4;
841 static final int GC_BACKGROUND_PROCESSES_MSG = 5;
842 static final int WAIT_FOR_DEBUGGER_MSG = 6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 static final int SERVICE_TIMEOUT_MSG = 12;
844 static final int UPDATE_TIME_ZONE = 13;
845 static final int SHOW_UID_ERROR_MSG = 14;
846 static final int IM_FEELING_LUCKY_MSG = 15;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 static final int PROC_START_TIMEOUT_MSG = 20;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700848 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -0700849 static final int KILL_APPLICATION_MSG = 22;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -0800850 static final int FINALIZE_PENDING_INTENT_MSG = 23;
Dianne Hackborn860755f2010-06-03 18:47:52 -0700851 static final int POST_HEAVY_NOTIFICATION_MSG = 24;
852 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700853 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -0700854 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27;
Robert Greenwalt03595d02010-11-02 14:08:23 -0700855 static final int CLEAR_DNS_CACHE = 28;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700856 static final int UPDATE_HTTP_PROXY = 29;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700857 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30;
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700858 static final int DISPATCH_PROCESSES_CHANGED = 31;
Dianne Hackborn36f80f32011-05-31 18:26:45 -0700859 static final int DISPATCH_PROCESS_DIED = 32;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700860 static final int REPORT_MEM_USAGE = 33;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800862 static final int FIRST_ACTIVITY_STACK_MSG = 100;
863 static final int FIRST_BROADCAST_QUEUE_MSG = 200;
864 static final int FIRST_COMPAT_MODE_MSG = 300;
865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 AlertDialog mUidAlert;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700867 CompatModeDialog mCompatModeDialog;
Dianne Hackborn04d6db32011-11-04 20:07:24 -0700868 long mLastMemUsageReportTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869
870 final Handler mHandler = new Handler() {
871 //public Handler() {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800872 // if (localLOGV) Slog.v(TAG, "Handler started!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 //}
874
875 public void handleMessage(Message msg) {
876 switch (msg.what) {
877 case SHOW_ERROR_MSG: {
878 HashMap data = (HashMap) msg.obj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 synchronized (ActivityManagerService.this) {
880 ProcessRecord proc = (ProcessRecord)data.get("app");
881 if (proc != null && proc.crashDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800882 Slog.e(TAG, "App already has crash dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 return;
884 }
885 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700886 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Dan Egnorb7f03672009-12-09 16:22:32 -0800887 Dialog d = new AppErrorDialog(mContext, res, proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 d.show();
889 proc.crashDialog = d;
890 } else {
891 // The device is asleep, so just pretend that the user
892 // saw a crash dialog and hit "force quit".
893 res.set(0);
894 }
895 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700896
897 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 } break;
899 case SHOW_NOT_RESPONDING_MSG: {
900 synchronized (ActivityManagerService.this) {
901 HashMap data = (HashMap) msg.obj;
902 ProcessRecord proc = (ProcessRecord)data.get("app");
903 if (proc != null && proc.anrDialog != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800904 Slog.e(TAG, "App already has anr dialog: " + proc);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 return;
906 }
The Android Open Source Project4df24232009-03-05 14:34:35 -0800907
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700908 Intent intent = new Intent("android.intent.action.ANR");
909 if (!mProcessesReady) {
Christopher Tatef46723b2012-01-26 14:19:24 -0800910 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
911 | Intent.FLAG_RECEIVER_FOREGROUND);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -0700912 }
913 broadcastIntentLocked(null, null, intent,
The Android Open Source Project4df24232009-03-05 14:34:35 -0800914 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -0700915 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800916
Justin Kohbc52ca22012-03-29 15:11:44 -0700917 if (mShowDialogs) {
918 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this,
Mike Lockwood69ccdbd2012-04-03 11:53:47 -0700919 mContext, proc, (ActivityRecord)data.get("activity"));
Justin Kohbc52ca22012-03-29 15:11:44 -0700920 d.show();
921 proc.anrDialog = d;
922 } else {
923 // Just kill the app if there is no dialog to be shown.
924 killAppAtUsersRequest(proc, null);
925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -0700927
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700928 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 } break;
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700930 case SHOW_STRICT_MODE_VIOLATION_MSG: {
931 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
932 synchronized (ActivityManagerService.this) {
933 ProcessRecord proc = (ProcessRecord) data.get("app");
934 if (proc == null) {
935 Slog.e(TAG, "App not found when showing strict mode dialog.");
936 break;
937 }
938 if (proc.crashDialog != null) {
939 Slog.e(TAG, "App already has strict mode dialog: " + proc);
940 return;
941 }
942 AppErrorResult res = (AppErrorResult) data.get("result");
Joe Onorato54a4a412011-11-02 20:50:08 -0700943 if (mShowDialogs && !mSleeping && !mShuttingDown) {
Brad Fitzpatrick438d0592010-06-10 12:19:19 -0700944 Dialog d = new StrictModeViolationDialog(mContext, res, proc);
945 d.show();
946 proc.crashDialog = d;
947 } else {
948 // The device is asleep, so just pretend that the user
949 // saw a crash dialog and hit "force quit".
950 res.set(0);
951 }
952 }
953 ensureBootCompleted();
954 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 case SHOW_FACTORY_ERROR_MSG: {
956 Dialog d = new FactoryErrorDialog(
957 mContext, msg.getData().getCharSequence("msg"));
958 d.show();
Dianne Hackborn9acc0302009-08-25 00:27:12 -0700959 ensureBootCompleted();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 } break;
961 case UPDATE_CONFIGURATION_MSG: {
962 final ContentResolver resolver = mContext.getContentResolver();
963 Settings.System.putConfiguration(resolver, (Configuration)msg.obj);
964 } break;
965 case GC_BACKGROUND_PROCESSES_MSG: {
966 synchronized (ActivityManagerService.this) {
967 performAppGcsIfAppropriateLocked();
968 }
969 } break;
970 case WAIT_FOR_DEBUGGER_MSG: {
971 synchronized (ActivityManagerService.this) {
972 ProcessRecord app = (ProcessRecord)msg.obj;
973 if (msg.arg1 != 0) {
974 if (!app.waitedForDebugger) {
975 Dialog d = new AppWaitingForDebuggerDialog(
976 ActivityManagerService.this,
977 mContext, app);
978 app.waitDialog = d;
979 app.waitedForDebugger = true;
980 d.show();
981 }
982 } else {
983 if (app.waitDialog != null) {
984 app.waitDialog.dismiss();
985 app.waitDialog = null;
986 }
987 }
988 }
989 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 case SERVICE_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700991 if (mDidDexOpt) {
992 mDidDexOpt = false;
993 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG);
994 nmsg.obj = msg.obj;
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700995 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700996 return;
997 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -0700998 mServices.serviceTimeout((ProcessRecord)msg.obj);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 } break;
1000 case UPDATE_TIME_ZONE: {
1001 synchronized (ActivityManagerService.this) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001002 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1003 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 if (r.thread != null) {
1005 try {
1006 r.thread.updateTimeZone();
1007 } catch (RemoteException ex) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001008 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 }
1010 }
1011 }
1012 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001013 } break;
Robert Greenwalt03595d02010-11-02 14:08:23 -07001014 case CLEAR_DNS_CACHE: {
1015 synchronized (ActivityManagerService.this) {
1016 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1017 ProcessRecord r = mLruProcesses.get(i);
1018 if (r.thread != null) {
1019 try {
1020 r.thread.clearDnsCache();
1021 } catch (RemoteException ex) {
1022 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName);
1023 }
1024 }
1025 }
1026 }
1027 } break;
Robert Greenwalt434203a2010-10-11 16:00:27 -07001028 case UPDATE_HTTP_PROXY: {
1029 ProxyProperties proxy = (ProxyProperties)msg.obj;
1030 String host = "";
1031 String port = "";
1032 String exclList = "";
1033 if (proxy != null) {
1034 host = proxy.getHost();
1035 port = Integer.toString(proxy.getPort());
1036 exclList = proxy.getExclusionList();
1037 }
1038 synchronized (ActivityManagerService.this) {
1039 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
1040 ProcessRecord r = mLruProcesses.get(i);
1041 if (r.thread != null) {
1042 try {
1043 r.thread.setHttpProxy(host, port, exclList);
1044 } catch (RemoteException ex) {
1045 Slog.w(TAG, "Failed to update http proxy for: " +
1046 r.info.processName);
1047 }
1048 }
1049 }
1050 }
1051 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 case SHOW_UID_ERROR_MSG: {
Joe Onorato54a4a412011-11-02 20:50:08 -07001053 String title = "System UIDs Inconsistent";
1054 String text = "UIDs on the system are inconsistent, you need to wipe your"
1055 + " data partition or your device will be unstable.";
1056 Log.e(TAG, title + ": " + text);
1057 if (mShowDialogs) {
1058 // XXX This is a temporary dialog, no need to localize.
1059 AlertDialog d = new BaseErrorDialog(mContext);
1060 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR);
1061 d.setCancelable(false);
1062 d.setTitle(title);
1063 d.setMessage(text);
1064 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky",
1065 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG));
1066 mUidAlert = d;
1067 d.show();
1068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 } break;
1070 case IM_FEELING_LUCKY_MSG: {
1071 if (mUidAlert != null) {
1072 mUidAlert.dismiss();
1073 mUidAlert = null;
1074 }
1075 } break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 case PROC_START_TIMEOUT_MSG: {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001077 if (mDidDexOpt) {
1078 mDidDexOpt = false;
1079 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
1080 nmsg.obj = msg.obj;
1081 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT);
1082 return;
1083 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 ProcessRecord app = (ProcessRecord)msg.obj;
1085 synchronized (ActivityManagerService.this) {
1086 processStartTimedOutLocked(app);
1087 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001088 } break;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07001089 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: {
1090 synchronized (ActivityManagerService.this) {
1091 doPendingActivityLaunchesLocked(true);
1092 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07001093 } break;
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001094 case KILL_APPLICATION_MSG: {
1095 synchronized (ActivityManagerService.this) {
1096 int uid = msg.arg1;
1097 boolean restart = (msg.arg2 == 1);
1098 String pkg = (String) msg.obj;
Amith Yamasani483f3b02012-03-13 16:08:00 -07001099 forceStopPackageLocked(pkg, uid, restart, false, true, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001100 UserHandle.getUserId(uid));
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07001101 }
1102 } break;
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08001103 case FINALIZE_PENDING_INTENT_MSG: {
1104 ((PendingIntentRecord)msg.obj).completeFinalize();
1105 } break;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001106 case POST_HEAVY_NOTIFICATION_MSG: {
1107 INotificationManager inm = NotificationManager.getService();
1108 if (inm == null) {
1109 return;
1110 }
1111
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001112 ActivityRecord root = (ActivityRecord)msg.obj;
Dianne Hackborn860755f2010-06-03 18:47:52 -07001113 ProcessRecord process = root.app;
1114 if (process == null) {
1115 return;
1116 }
1117
1118 try {
1119 Context context = mContext.createPackageContext(process.info.packageName, 0);
1120 String text = mContext.getString(R.string.heavy_weight_notification,
1121 context.getApplicationInfo().loadLabel(context.getPackageManager()));
1122 Notification notification = new Notification();
1123 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon;
1124 notification.when = 0;
1125 notification.flags = Notification.FLAG_ONGOING_EVENT;
1126 notification.tickerText = text;
1127 notification.defaults = 0; // please be quiet
1128 notification.sound = null;
1129 notification.vibrate = null;
1130 notification.setLatestEventInfo(context, text,
1131 mContext.getText(R.string.heavy_weight_notification_detail),
Dianne Hackborn41203752012-08-31 14:05:51 -07001132 PendingIntent.getActivityAsUser(mContext, 0, root.intent,
1133 PendingIntent.FLAG_CANCEL_CURRENT, null,
1134 new UserHandle(root.userId)));
Dianne Hackborn860755f2010-06-03 18:47:52 -07001135
1136 try {
1137 int[] outId = new int[1];
Dianne Hackborn41203752012-08-31 14:05:51 -07001138 inm.enqueueNotificationWithTag("android", null,
1139 R.string.heavy_weight_notification,
1140 notification, outId, root.userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001141 } catch (RuntimeException e) {
1142 Slog.w(ActivityManagerService.TAG,
1143 "Error showing notification for heavy-weight app", e);
1144 } catch (RemoteException e) {
1145 }
1146 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001147 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001148 }
1149 } break;
1150 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1151 INotificationManager inm = NotificationManager.getService();
1152 if (inm == null) {
1153 return;
1154 }
1155 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07001156 inm.cancelNotificationWithTag("android", null,
1157 R.string.heavy_weight_notification, msg.arg1);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001158 } catch (RuntimeException e) {
1159 Slog.w(ActivityManagerService.TAG,
1160 "Error canceling notification for service", e);
1161 } catch (RemoteException e) {
1162 }
1163 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001164 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1165 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001166 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001167 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001168 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1169 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001170 }
1171 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001172 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1173 synchronized (ActivityManagerService.this) {
1174 ActivityRecord ar = (ActivityRecord)msg.obj;
1175 if (mCompatModeDialog != null) {
1176 if (mCompatModeDialog.mAppInfo.packageName.equals(
1177 ar.info.applicationInfo.packageName)) {
1178 return;
1179 }
1180 mCompatModeDialog.dismiss();
1181 mCompatModeDialog = null;
1182 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001183 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001184 if (mCompatModePackages.getPackageAskCompatModeLocked(
1185 ar.packageName)) {
1186 int mode = mCompatModePackages.computeCompatModeLocked(
1187 ar.info.applicationInfo);
1188 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1189 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1190 mCompatModeDialog = new CompatModeDialog(
1191 ActivityManagerService.this, mContext,
1192 ar.info.applicationInfo);
1193 mCompatModeDialog.show();
1194 }
1195 }
1196 }
1197 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001198 break;
1199 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001200 case DISPATCH_PROCESSES_CHANGED: {
1201 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001202 break;
1203 }
1204 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001205 final int pid = msg.arg1;
1206 final int uid = msg.arg2;
1207 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001208 break;
1209 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001210 case REPORT_MEM_USAGE: {
1211 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1212 if (!isDebuggable) {
1213 return;
1214 }
1215 synchronized (ActivityManagerService.this) {
1216 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001217 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1218 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001219 // avoid spamming.
1220 return;
1221 }
1222 mLastMemUsageReportTime = now;
1223 }
1224 Thread thread = new Thread() {
1225 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001226 StringBuilder dropBuilder = new StringBuilder(1024);
1227 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001228 StringWriter oomSw = new StringWriter();
1229 PrintWriter oomPw = new PrintWriter(oomSw);
1230 StringWriter catSw = new StringWriter();
1231 PrintWriter catPw = new PrintWriter(catSw);
1232 String[] emptyArgs = new String[] { };
1233 StringBuilder tag = new StringBuilder(128);
1234 StringBuilder stack = new StringBuilder(128);
1235 tag.append("Low on memory -- ");
1236 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1237 tag, stack);
1238 dropBuilder.append(stack);
1239 dropBuilder.append('\n');
1240 dropBuilder.append('\n');
1241 String oomString = oomSw.toString();
1242 dropBuilder.append(oomString);
1243 dropBuilder.append('\n');
1244 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001245 try {
1246 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1247 "procrank", });
1248 final InputStreamReader converter = new InputStreamReader(
1249 proc.getInputStream());
1250 BufferedReader in = new BufferedReader(converter);
1251 String line;
1252 while (true) {
1253 line = in.readLine();
1254 if (line == null) {
1255 break;
1256 }
1257 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001258 logBuilder.append(line);
1259 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001260 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001261 dropBuilder.append(line);
1262 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001263 }
1264 converter.close();
1265 } catch (IOException e) {
1266 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001267 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001268 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001269 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001270 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001271 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1272 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001273 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001274 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001275 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001276 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001277 addErrorToDropBox("lowmem", null, "system_server", null,
1278 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001279 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001280 synchronized (ActivityManagerService.this) {
1281 long now = SystemClock.uptimeMillis();
1282 if (mLastMemUsageReportTime < now) {
1283 mLastMemUsageReportTime = now;
1284 }
1285 }
1286 }
1287 };
1288 thread.start();
1289 break;
1290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 }
1292 }
1293 };
1294
1295 public static void setSystemProcess() {
1296 try {
1297 ActivityManagerService m = mSelf;
1298
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001299 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001301 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001302 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 if (MONITOR_CPU_USAGE) {
1304 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 ServiceManager.addService("permission", new PermissionController(m));
1307
1308 ApplicationInfo info =
1309 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001310 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001311 mSystemThread.installSystemApplicationInfo(info);
1312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 synchronized (mSelf) {
1314 ProcessRecord app = mSelf.newProcessRecordLocked(
1315 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001316 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001318 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001319 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001320 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 synchronized (mSelf.mPidsSelfLocked) {
1322 mSelf.mPidsSelfLocked.put(app.pid, app);
1323 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001324 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 }
1326 } catch (PackageManager.NameNotFoundException e) {
1327 throw new RuntimeException(
1328 "Unable to find android system package", e);
1329 }
1330 }
1331
1332 public void setWindowManager(WindowManagerService wm) {
1333 mWindowManager = wm;
1334 }
1335
1336 public static final Context main(int factoryTest) {
1337 AThread thr = new AThread();
1338 thr.start();
1339
1340 synchronized (thr) {
1341 while (thr.mService == null) {
1342 try {
1343 thr.wait();
1344 } catch (InterruptedException e) {
1345 }
1346 }
1347 }
1348
1349 ActivityManagerService m = thr.mService;
1350 mSelf = m;
1351 ActivityThread at = ActivityThread.systemMain();
1352 mSystemThread = at;
1353 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001354 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 m.mContext = context;
1356 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001357 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358
1359 m.mBatteryStatsService.publish(context);
1360 m.mUsageStatsService.publish(context);
1361
1362 synchronized (thr) {
1363 thr.mReady = true;
1364 thr.notifyAll();
1365 }
1366
1367 m.startRunning(null, null, null, null);
1368
1369 return context;
1370 }
1371
1372 public static ActivityManagerService self() {
1373 return mSelf;
1374 }
1375
1376 static class AThread extends Thread {
1377 ActivityManagerService mService;
1378 boolean mReady = false;
1379
1380 public AThread() {
1381 super("ActivityManager");
1382 }
1383
1384 public void run() {
1385 Looper.prepare();
1386
1387 android.os.Process.setThreadPriority(
1388 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001389 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390
1391 ActivityManagerService m = new ActivityManagerService();
1392
1393 synchronized (this) {
1394 mService = m;
1395 notifyAll();
1396 }
1397
1398 synchronized (this) {
1399 while (!mReady) {
1400 try {
1401 wait();
1402 } catch (InterruptedException e) {
1403 }
1404 }
1405 }
1406
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001407 // For debug builds, log event loop stalls to dropbox for analysis.
1408 if (StrictMode.conditionallyEnableDebugLogging()) {
1409 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1410 }
1411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 Looper.loop();
1413 }
1414 }
1415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 static class MemBinder extends Binder {
1417 ActivityManagerService mActivityManagerService;
1418 MemBinder(ActivityManagerService activityManagerService) {
1419 mActivityManagerService = activityManagerService;
1420 }
1421
1422 @Override
1423 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001424 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1425 != PackageManager.PERMISSION_GRANTED) {
1426 pw.println("Permission Denial: can't dump meminfo from from pid="
1427 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1428 + " without permission " + android.Manifest.permission.DUMP);
1429 return;
1430 }
1431
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001432 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001433 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 }
1435 }
1436
Chet Haase9c1e23b2011-03-24 10:51:31 -07001437 static class GraphicsBinder extends Binder {
1438 ActivityManagerService mActivityManagerService;
1439 GraphicsBinder(ActivityManagerService activityManagerService) {
1440 mActivityManagerService = activityManagerService;
1441 }
1442
1443 @Override
1444 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001445 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1446 != PackageManager.PERMISSION_GRANTED) {
1447 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1448 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1449 + " without permission " + android.Manifest.permission.DUMP);
1450 return;
1451 }
1452
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001453 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001454 }
1455 }
1456
Jeff Brown6754ba22011-12-14 20:20:01 -08001457 static class DbBinder extends Binder {
1458 ActivityManagerService mActivityManagerService;
1459 DbBinder(ActivityManagerService activityManagerService) {
1460 mActivityManagerService = activityManagerService;
1461 }
1462
1463 @Override
1464 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1465 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1466 != PackageManager.PERMISSION_GRANTED) {
1467 pw.println("Permission Denial: can't dump dbinfo from from pid="
1468 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1469 + " without permission " + android.Manifest.permission.DUMP);
1470 return;
1471 }
1472
1473 mActivityManagerService.dumpDbInfo(fd, pw, args);
1474 }
1475 }
1476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 static class CpuBinder extends Binder {
1478 ActivityManagerService mActivityManagerService;
1479 CpuBinder(ActivityManagerService activityManagerService) {
1480 mActivityManagerService = activityManagerService;
1481 }
1482
1483 @Override
1484 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001485 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1486 != PackageManager.PERMISSION_GRANTED) {
1487 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1488 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1489 + " without permission " + android.Manifest.permission.DUMP);
1490 return;
1491 }
1492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001494 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1495 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1496 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 }
1498 }
1499 }
1500
1501 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001502 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001503
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001504 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1505 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1506 mBroadcastQueues[0] = mFgBroadcastQueue;
1507 mBroadcastQueues[1] = mBgBroadcastQueue;
1508
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001509 mServices = new ActiveServices(this);
1510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 File dataDir = Environment.getDataDirectory();
1512 File systemDir = new File(dataDir, "system");
1513 systemDir.mkdirs();
1514 mBatteryStatsService = new BatteryStatsService(new File(
1515 systemDir, "batterystats.bin").toString());
1516 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001517 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001518 mOnBattery = DEBUG_POWER ? true
1519 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001520 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001522 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001523 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001524 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001526 // User 0 is the first and only user that runs at boot.
1527 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
1528
Jack Palevichb90d28c2009-07-22 15:35:24 -07001529 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1530 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1531
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001532 mConfiguration.setToDefaults();
1533 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001534 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 mProcessStats.init();
1536
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001537 mCompatModePackages = new CompatModePackages(this, systemDir);
1538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 // Add ourself to the Watchdog monitors.
1540 Watchdog.getInstance().addMonitor(this);
1541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 mProcessStatsThread = new Thread("ProcessStats") {
1543 public void run() {
1544 while (true) {
1545 try {
1546 try {
1547 synchronized(this) {
1548 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001549 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001551 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 // + ", write delay=" + nextWriteDelay);
1553 if (nextWriteDelay < nextCpuDelay) {
1554 nextCpuDelay = nextWriteDelay;
1555 }
1556 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001557 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 this.wait(nextCpuDelay);
1559 }
1560 }
1561 } catch (InterruptedException e) {
1562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 updateCpuStatsNow();
1564 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001565 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 }
1567 }
1568 }
1569 };
1570 mProcessStatsThread.start();
1571 }
1572
1573 @Override
1574 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1575 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001576 if (code == SYSPROPS_TRANSACTION) {
1577 // We need to tell all apps about the system property change.
1578 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1579 synchronized(this) {
1580 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1581 final int NA = apps.size();
1582 for (int ia=0; ia<NA; ia++) {
1583 ProcessRecord app = apps.valueAt(ia);
1584 if (app.thread != null) {
1585 procs.add(app.thread.asBinder());
1586 }
1587 }
1588 }
1589 }
1590
1591 int N = procs.size();
1592 for (int i=0; i<N; i++) {
1593 Parcel data2 = Parcel.obtain();
1594 try {
1595 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1596 } catch (RemoteException e) {
1597 }
1598 data2.recycle();
1599 }
1600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601 try {
1602 return super.onTransact(code, data, reply, flags);
1603 } catch (RuntimeException e) {
1604 // The activity manager only throws security exceptions, so let's
1605 // log all others.
1606 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001607 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 }
1609 throw e;
1610 }
1611 }
1612
1613 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001614 final long now = SystemClock.uptimeMillis();
1615 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1616 return;
1617 }
1618 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1619 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 mProcessStatsThread.notify();
1621 }
1622 }
1623 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001625 void updateCpuStatsNow() {
1626 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001627 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 final long now = SystemClock.uptimeMillis();
1629 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001631 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001632 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1633 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 haveNewCpuStats = true;
1635 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001636 //Slog.i(TAG, mProcessStats.printCurrentState());
1637 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 // + mProcessStats.getTotalCpuPercent() + "%");
1639
Joe Onorato8a9b2202010-02-26 18:56:32 -08001640 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 if ("true".equals(SystemProperties.get("events.cpu"))) {
1642 int user = mProcessStats.getLastUserTime();
1643 int system = mProcessStats.getLastSystemTime();
1644 int iowait = mProcessStats.getLastIoWaitTime();
1645 int irq = mProcessStats.getLastIrqTime();
1646 int softIrq = mProcessStats.getLastSoftIrqTime();
1647 int idle = mProcessStats.getLastIdleTime();
1648
1649 int total = user + system + iowait + irq + softIrq + idle;
1650 if (total == 0) total = 1;
1651
Doug Zongker2bec3d42009-12-04 12:52:44 -08001652 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 ((user+system+iowait+irq+softIrq) * 100) / total,
1654 (user * 100) / total,
1655 (system * 100) / total,
1656 (iowait * 100) / total,
1657 (irq * 100) / total,
1658 (softIrq * 100) / total);
1659 }
1660 }
1661
Amith Yamasanie43530a2009-08-21 13:11:37 -07001662 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001663 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001664 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 synchronized(mPidsSelfLocked) {
1666 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001667 if (mOnBattery) {
1668 int perc = bstats.startAddingCpuLocked();
1669 int totalUTime = 0;
1670 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001671 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001673 ProcessStats.Stats st = mProcessStats.getStats(i);
1674 if (!st.working) {
1675 continue;
1676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001677 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001678 int otherUTime = (st.rel_utime*perc)/100;
1679 int otherSTime = (st.rel_stime*perc)/100;
1680 totalUTime += otherUTime;
1681 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 if (pr != null) {
1683 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001684 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1685 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001686 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001687 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001688 } else {
1689 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001690 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001691 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001692 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1693 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001694 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 }
1697 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001698 bstats.finishAddingCpuLocked(perc, totalUTime,
1699 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 }
1701 }
1702 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1705 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001706 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 }
1708 }
1709 }
1710 }
1711
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001712 @Override
1713 public void batteryNeedsCpuUpdate() {
1714 updateCpuStatsNow();
1715 }
1716
1717 @Override
1718 public void batteryPowerChanged(boolean onBattery) {
1719 // When plugging in, update the CPU stats first before changing
1720 // the plug state.
1721 updateCpuStatsNow();
1722 synchronized (this) {
1723 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001724 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001725 }
1726 }
1727 }
1728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 /**
1730 * Initialize the application bind args. These are passed to each
1731 * process when the bindApplication() IPC is sent to the process. They're
1732 * lazily setup to make sure the services are running when they're asked for.
1733 */
1734 private HashMap<String, IBinder> getCommonServicesLocked() {
1735 if (mAppBindArgs == null) {
1736 mAppBindArgs = new HashMap<String, IBinder>();
1737
1738 // Setup the application init args
1739 mAppBindArgs.put("package", ServiceManager.getService("package"));
1740 mAppBindArgs.put("window", ServiceManager.getService("window"));
1741 mAppBindArgs.put(Context.ALARM_SERVICE,
1742 ServiceManager.getService(Context.ALARM_SERVICE));
1743 }
1744 return mAppBindArgs;
1745 }
1746
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001747 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 if (mFocusedActivity != r) {
1749 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001750 if (r != null) {
1751 mWindowManager.setFocusedApp(r.appToken, true);
1752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 }
1754 }
1755
Dianne Hackborn906497c2010-05-10 15:57:38 -07001756 private final void updateLruProcessInternalLocked(ProcessRecord app,
1757 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001759 int lrui = mLruProcesses.indexOf(app);
1760 if (lrui >= 0) mLruProcesses.remove(lrui);
1761
1762 int i = mLruProcesses.size()-1;
1763 int skipTop = 0;
1764
Dianne Hackborn906497c2010-05-10 15:57:38 -07001765 app.lruSeq = mLruSeq;
1766
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001767 // compute the new weight for this process.
1768 if (updateActivityTime) {
1769 app.lastActivityTime = SystemClock.uptimeMillis();
1770 }
1771 if (app.activities.size() > 0) {
1772 // If this process has activities, we more strongly want to keep
1773 // it around.
1774 app.lruWeight = app.lastActivityTime;
1775 } else if (app.pubProviders.size() > 0) {
1776 // If this process contains content providers, we want to keep
1777 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001778 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001779 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001780 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001781 } else {
1782 // If this process doesn't have activities, we less strongly
1783 // want to keep it around, and generally want to avoid getting
1784 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001785 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001786 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001787 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001788 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001789
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001790 while (i >= 0) {
1791 ProcessRecord p = mLruProcesses.get(i);
1792 // If this app shouldn't be in front of the first N background
1793 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001794 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001795 skipTop--;
1796 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001797 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001798 mLruProcesses.add(i+1, app);
1799 break;
1800 }
1801 i--;
1802 }
1803 if (i < 0) {
1804 mLruProcesses.add(0, app);
1805 }
1806
Dianne Hackborn906497c2010-05-10 15:57:38 -07001807 // If the app is currently using a content provider or service,
1808 // bump those processes as well.
1809 if (app.connections.size() > 0) {
1810 for (ConnectionRecord cr : app.connections) {
1811 if (cr.binding != null && cr.binding.service != null
1812 && cr.binding.service.app != null
1813 && cr.binding.service.app.lruSeq != mLruSeq) {
Björn Davidsson90f9e312010-11-18 08:26:27 +01001814 updateLruProcessInternalLocked(cr.binding.service.app, false,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001815 updateActivityTime, i+1);
1816 }
1817 }
1818 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001819 for (int j=app.conProviders.size()-1; j>=0; j--) {
1820 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1821 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Jean-Baptiste Querub8c64052012-06-11 11:01:19 -07001822 updateLruProcessInternalLocked(cpr.proc, false,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001823 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001824 }
1825 }
1826
Joe Onorato8a9b2202010-02-26 18:56:32 -08001827 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 if (oomAdj) {
1829 updateOomAdjLocked();
1830 }
1831 }
1832
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001833 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001834 boolean oomAdj, boolean updateActivityTime) {
1835 mLruSeq++;
1836 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1837 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001838
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001839 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001841 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001842 // The system gets to run in any process. If there are multiple
1843 // processes with the same uid, just pick the first (this
1844 // should never happen).
1845 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1846 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001847 if (procs == null) return null;
1848 final int N = procs.size();
1849 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001850 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 }
1853 ProcessRecord proc = mProcessNames.get(processName, uid);
1854 return proc;
1855 }
1856
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001857 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001858 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001859 try {
1860 if (pm.performDexOpt(packageName)) {
1861 mDidDexOpt = true;
1862 }
1863 } catch (RemoteException e) {
1864 }
1865 }
1866
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001867 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 int transit = mWindowManager.getPendingAppTransition();
1869 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1870 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1871 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1872 }
1873
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001874 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001876 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1877 boolean isolated) {
1878 ProcessRecord app;
1879 if (!isolated) {
1880 app = getProcessRecordLocked(processName, info.uid);
1881 } else {
1882 // If this is an isolated process, it can't re-use an existing process.
1883 app = null;
1884 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 // We don't have to do anything more if:
1886 // (1) There is an existing application record; and
1887 // (2) The caller doesn't think it is dead, OR there is no thread
1888 // object attached to it so we know it couldn't have crashed; and
1889 // (3) There is a pid assigned to it, so it is either starting or
1890 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001891 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 + " app=" + app + " knownToBeDead=" + knownToBeDead
1893 + " thread=" + (app != null ? app.thread : null)
1894 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001895 if (app != null && app.pid > 0) {
1896 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001897 // We already have the app running, or are waiting for it to
1898 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001899 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001900 // If this is a new package in the process, add the package to the list
1901 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001902 return app;
1903 } else {
1904 // An application record is attached to a previous process,
1905 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001906 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001907 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001910
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 String hostingNameStr = hostingName != null
1912 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001913
1914 if (!isolated) {
1915 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1916 // If we are in the background, then check to see if this process
1917 // is bad. If so, we will just silently fail.
1918 if (mBadProcesses.get(info.processName, info.uid) != null) {
1919 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1920 + "/" + info.processName);
1921 return null;
1922 }
1923 } else {
1924 // When the user is explicitly starting a process, then clear its
1925 // crash count so that we won't make it bad until they see at
1926 // least one crash dialog again, and make the process good again
1927 // if it had been bad.
1928 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001929 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001930 mProcessCrashTimes.remove(info.processName, info.uid);
1931 if (mBadProcesses.get(info.processName, info.uid) != null) {
1932 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1933 info.processName);
1934 mBadProcesses.remove(info.processName, info.uid);
1935 if (app != null) {
1936 app.bad = false;
1937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 }
1939 }
1940 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001943 app = newProcessRecordLocked(null, info, processName, isolated);
1944 if (app == null) {
1945 Slog.w(TAG, "Failed making new process record for "
1946 + processName + "/" + info.uid + " isolated=" + isolated);
1947 return null;
1948 }
1949 mProcessNames.put(processName, app.uid, app);
1950 if (isolated) {
1951 mIsolatedProcesses.put(app.uid, app);
1952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001953 } else {
1954 // If this is a new package in the process, add the package to the list
1955 app.addPackage(info.packageName);
1956 }
1957
1958 // If the system is not ready yet, then hold off on starting this
1959 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001960 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001961 && !isAllowedWhileBooting(info)
1962 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 if (!mProcessesOnHold.contains(app)) {
1964 mProcessesOnHold.add(app);
1965 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001966 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 return app;
1968 }
1969
1970 startProcessLocked(app, hostingType, hostingNameStr);
1971 return (app.pid != 0) ? app : null;
1972 }
1973
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001974 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1975 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1976 }
1977
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 private final void startProcessLocked(ProcessRecord app,
1979 String hostingType, String hostingNameStr) {
1980 if (app.pid > 0 && app.pid != MY_PID) {
1981 synchronized (mPidsSelfLocked) {
1982 mPidsSelfLocked.remove(app.pid);
1983 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1984 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001985 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 }
1987
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001988 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1989 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 mProcessesOnHold.remove(app);
1991
1992 updateCpuStats();
1993
1994 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1995 mProcDeaths[0] = 0;
1996
1997 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001998 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001999
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002001 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002002 if (!app.isolated) {
2003 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002004 final PackageManager pm = mContext.getPackageManager();
2005 gids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002006
2007 if (Environment.isExternalStorageEmulated()) {
2008 if (pm.checkPermission(
2009 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2010 app.info.packageName) == PERMISSION_GRANTED) {
2011 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2012 } else {
2013 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2014 }
2015 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002016 } catch (PackageManager.NameNotFoundException e) {
2017 Slog.w(TAG, "Unable to retrieve gids", e);
2018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 }
2020 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2021 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2022 && mTopComponent != null
2023 && app.processName.equals(mTopComponent.getPackageName())) {
2024 uid = 0;
2025 }
2026 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2027 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2028 uid = 0;
2029 }
2030 }
2031 int debugFlags = 0;
2032 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2033 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002034 // Also turn on CheckJNI for debuggable apps. It's quite
2035 // awkward to turn on otherwise.
2036 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002038 // Run the app in safe mode if its manifest requests so or the
2039 // system is booted in safe mode.
2040 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2041 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002042 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2045 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2046 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002047 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2048 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 if ("1".equals(SystemProperties.get("debug.assert"))) {
2051 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2052 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002053
2054 // Start the process. It will either succeed and return a result containing
2055 // the PID of the new process, or else throw a RuntimeException.
2056 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002057 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002058 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2061 synchronized (bs) {
2062 if (bs.isOnBattery()) {
2063 app.batteryStats.incStartsLocked();
2064 }
2065 }
2066
Jeff Brown3f9dd282011-07-08 20:02:19 -07002067 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 app.processName, hostingType,
2069 hostingNameStr != null ? hostingNameStr : "");
2070
2071 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002072 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 }
2074
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002075 StringBuilder buf = mStringBuilder;
2076 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 buf.append("Start proc ");
2078 buf.append(app.processName);
2079 buf.append(" for ");
2080 buf.append(hostingType);
2081 if (hostingNameStr != null) {
2082 buf.append(" ");
2083 buf.append(hostingNameStr);
2084 }
2085 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002086 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 buf.append(" uid=");
2088 buf.append(uid);
2089 buf.append(" gids={");
2090 if (gids != null) {
2091 for (int gi=0; gi<gids.length; gi++) {
2092 if (gi != 0) buf.append(", ");
2093 buf.append(gids[gi]);
2094
2095 }
2096 }
2097 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002098 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002099 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002100 app.usingWrapper = startResult.usingWrapper;
2101 app.removed = false;
2102 synchronized (mPidsSelfLocked) {
2103 this.mPidsSelfLocked.put(startResult.pid, app);
2104 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2105 msg.obj = app;
2106 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2107 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 }
2109 } catch (RuntimeException e) {
2110 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002111 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002112 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 }
2114 }
2115
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002116 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 if (resumed) {
2118 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2119 } else {
2120 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2121 }
2122 }
2123
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002124 boolean startHomeActivityLocked(int userId, UserStartedState startingUser) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002125 if (mHeadless) {
2126 // Added because none of the other calls to ensureBootCompleted seem to fire
2127 // when running headless.
2128 ensureBootCompleted();
2129 return false;
2130 }
2131
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002132 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2133 && mTopAction == null) {
2134 // We are running in factory test mode, but unable to find
2135 // the factory test app, so just sit around displaying the
2136 // error message and don't try to start anything.
2137 return false;
2138 }
2139 Intent intent = new Intent(
2140 mTopAction,
2141 mTopData != null ? Uri.parse(mTopData) : null);
2142 intent.setComponent(mTopComponent);
2143 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2144 intent.addCategory(Intent.CATEGORY_HOME);
2145 }
2146 ActivityInfo aInfo =
2147 intent.resolveActivityInfo(mContext.getPackageManager(),
2148 STOCK_PM_FLAGS);
2149 if (aInfo != null) {
2150 intent.setComponent(new ComponentName(
2151 aInfo.applicationInfo.packageName, aInfo.name));
2152 // Don't do this if the home app is currently being
2153 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002154 aInfo = new ActivityInfo(aInfo);
2155 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002156 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2157 aInfo.applicationInfo.uid);
2158 if (app == null || app.instrumentationClass == null) {
2159 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002160 mMainStack.startActivityLocked(null, intent, null, aInfo,
2161 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002162 }
2163 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002164 if (startingUser != null) {
2165 mMainStack.addStartingUserLocked(startingUser);
2166 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002167
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002168 return true;
2169 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002170
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002171 /**
2172 * Starts the "new version setup screen" if appropriate.
2173 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002174 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002175 // Only do this once per boot.
2176 if (mCheckedForSetup) {
2177 return;
2178 }
2179
2180 // We will show this screen if the current one is a different
2181 // version than the last one shown, and we are not running in
2182 // low-level factory test mode.
2183 final ContentResolver resolver = mContext.getContentResolver();
2184 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2185 Settings.Secure.getInt(resolver,
2186 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2187 mCheckedForSetup = true;
2188
2189 // See if we should be showing the platform update setup UI.
2190 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2191 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2192 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2193
2194 // We don't allow third party apps to replace this.
2195 ResolveInfo ri = null;
2196 for (int i=0; ris != null && i<ris.size(); i++) {
2197 if ((ris.get(i).activityInfo.applicationInfo.flags
2198 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2199 ri = ris.get(i);
2200 break;
2201 }
2202 }
2203
2204 if (ri != null) {
2205 String vers = ri.activityInfo.metaData != null
2206 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2207 : null;
2208 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2209 vers = ri.activityInfo.applicationInfo.metaData.getString(
2210 Intent.METADATA_SETUP_VERSION);
2211 }
2212 String lastVers = Settings.Secure.getString(
2213 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2214 if (vers != null && !vers.equals(lastVers)) {
2215 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2216 intent.setComponent(new ComponentName(
2217 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002218 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2219 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002220 }
2221 }
2222 }
2223 }
2224
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002225 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002226 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002227 }
2228
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002229 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002230 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002231 throw new SecurityException("Isolated process not allowed to call " + caller);
2232 }
2233 }
2234
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002235 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002236 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002237 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002238 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2239 }
2240 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002241
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002242 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002243 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2244 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002245 synchronized (this) {
2246 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2247 }
2248 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002249
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002250 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002251 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002252 synchronized (this) {
2253 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2254 }
2255 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002256
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002257 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002258 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2259 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002260 synchronized (this) {
2261 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002262 }
2263 }
2264
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002265 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002266 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002267 synchronized (this) {
2268 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2269 }
2270 }
2271
2272 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002273 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2274 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002275 synchronized (this) {
2276 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2277 }
2278 }
2279
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002280 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002281 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002282 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002284
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002285 private void dispatchProcessesChanged() {
2286 int N;
2287 synchronized (this) {
2288 N = mPendingProcessChanges.size();
2289 if (mActiveProcessChanges.length < N) {
2290 mActiveProcessChanges = new ProcessChangeItem[N];
2291 }
2292 mPendingProcessChanges.toArray(mActiveProcessChanges);
2293 mAvailProcessChanges.addAll(mPendingProcessChanges);
2294 mPendingProcessChanges.clear();
2295 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2296 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002297 int i = mProcessObservers.beginBroadcast();
2298 while (i > 0) {
2299 i--;
2300 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2301 if (observer != null) {
2302 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002303 for (int j=0; j<N; j++) {
2304 ProcessChangeItem item = mActiveProcessChanges[j];
2305 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2306 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2307 + item.pid + " uid=" + item.uid + ": "
2308 + item.foregroundActivities);
2309 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2310 item.foregroundActivities);
2311 }
2312 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2313 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2314 + item.pid + " uid=" + item.uid + ": " + item.importance);
2315 observer.onImportanceChanged(item.pid, item.uid,
2316 item.importance);
2317 }
2318 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002319 } catch (RemoteException e) {
2320 }
2321 }
2322 }
2323 mProcessObservers.finishBroadcast();
2324 }
2325
2326 private void dispatchProcessDied(int pid, int uid) {
2327 int i = mProcessObservers.beginBroadcast();
2328 while (i > 0) {
2329 i--;
2330 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2331 if (observer != null) {
2332 try {
2333 observer.onProcessDied(pid, uid);
2334 } catch (RemoteException e) {
2335 }
2336 }
2337 }
2338 mProcessObservers.finishBroadcast();
2339 }
2340
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002341 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002342 final int N = mPendingActivityLaunches.size();
2343 if (N <= 0) {
2344 return;
2345 }
2346 for (int i=0; i<N; i++) {
2347 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002348 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002349 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002350 }
2351 mPendingActivityLaunches.clear();
2352 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002353
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002354 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002355 Intent intent, String resolvedType, IBinder resultTo,
2356 String resultWho, int requestCode, int startFlags,
2357 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002358 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002359 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002360 }
2361
2362 public final int startActivityAsUser(IApplicationThread caller,
2363 Intent intent, String resolvedType, IBinder resultTo,
2364 String resultWho, int requestCode, int startFlags,
2365 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002366 enforceNotIsolatedCaller("startActivity");
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002367 if (userId != UserHandle.getCallingUserId()) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002368 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2369 false, true, "startActivity", null);
Amith Yamasani82644082012-08-03 13:09:11 -07002370 } else {
2371 if (intent.getCategories() != null
2372 && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2373 // Requesting home, set the identity to the current user
2374 // HACK!
2375 userId = mCurrentUserId;
Amith Yamasani742a6712011-05-04 14:49:28 -07002376 }
2377 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002378 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002379 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2380 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002381 }
2382
2383 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002384 Intent intent, String resolvedType, IBinder resultTo,
2385 String resultWho, int requestCode, int startFlags, String profileFile,
2386 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002387 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002388 WaitResult res = new WaitResult();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002389 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002390 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
Dianne Hackborn41203752012-08-31 14:05:51 -07002391 res, null, options, UserHandle.getCallingUserId());
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002392 return res;
2393 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002394
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002395 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002396 Intent intent, String resolvedType, IBinder resultTo,
2397 String resultWho, int requestCode, int startFlags, Configuration config,
Dianne Hackborn41203752012-08-31 14:05:51 -07002398 Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002399 enforceNotIsolatedCaller("startActivityWithConfig");
Dianne Hackborn41203752012-08-31 14:05:51 -07002400 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2401 false, true, "startActivityWithConfig", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002402 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002403 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002404 null, null, null, config, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002405 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002406 }
2407
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002408 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002409 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002410 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002411 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002412 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002413 // Refuse possible leaked file descriptors
2414 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2415 throw new IllegalArgumentException("File descriptors passed in Intent");
2416 }
2417
2418 IIntentSender sender = intent.getTarget();
2419 if (!(sender instanceof PendingIntentRecord)) {
2420 throw new IllegalArgumentException("Bad PendingIntent object");
2421 }
2422
2423 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002424
2425 synchronized (this) {
2426 // If this is coming from the currently resumed activity, it is
2427 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002428 if (mMainStack.mResumedActivity != null
2429 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002430 Binder.getCallingUid()) {
2431 mAppSwitchesAllowedTime = 0;
2432 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002433 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002434 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2435 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002436 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002437 }
2438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002440 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002441 // Refuse possible leaked file descriptors
2442 if (intent != null && intent.hasFileDescriptors() == true) {
2443 throw new IllegalArgumentException("File descriptors passed in Intent");
2444 }
2445
2446 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002447 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2448 if (r == null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002449 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 return false;
2451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 if (r.app == null || r.app.thread == null) {
2453 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002454 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 return false;
2456 }
2457 intent = new Intent(intent);
2458 // The caller is not allowed to change the data.
2459 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2460 // And we are resetting to find the next component...
2461 intent.setComponent(null);
2462
2463 ActivityInfo aInfo = null;
2464 try {
2465 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002466 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002468 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002469 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470
2471 // Look for the original activity in the list...
2472 final int N = resolves != null ? resolves.size() : 0;
2473 for (int i=0; i<N; i++) {
2474 ResolveInfo rInfo = resolves.get(i);
2475 if (rInfo.activityInfo.packageName.equals(r.packageName)
2476 && rInfo.activityInfo.name.equals(r.info.name)) {
2477 // We found the current one... the next matching is
2478 // after it.
2479 i++;
2480 if (i<N) {
2481 aInfo = resolves.get(i).activityInfo;
2482 }
2483 break;
2484 }
2485 }
2486 } catch (RemoteException e) {
2487 }
2488
2489 if (aInfo == null) {
2490 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002491 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 return false;
2493 }
2494
2495 intent.setComponent(new ComponentName(
2496 aInfo.applicationInfo.packageName, aInfo.name));
2497 intent.setFlags(intent.getFlags()&~(
2498 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2499 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2500 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2501 Intent.FLAG_ACTIVITY_NEW_TASK));
2502
2503 // Okay now we need to start the new activity, replacing the
2504 // currently running activity. This is a little tricky because
2505 // we want to start the new one as if the current one is finished,
2506 // but not finish the current one first so that there is no flicker.
2507 // And thus...
2508 final boolean wasFinishing = r.finishing;
2509 r.finishing = true;
2510
2511 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002512 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 final String resultWho = r.resultWho;
2514 final int requestCode = r.requestCode;
2515 r.resultTo = null;
2516 if (resultTo != null) {
2517 resultTo.removeResultsLocked(r, resultWho, requestCode);
2518 }
2519
2520 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002521 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002522 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2523 resultWho, requestCode, -1, r.launchedFromUid, 0,
2524 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 Binder.restoreCallingIdentity(origId);
2526
2527 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002528 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 return false;
2530 }
2531 return true;
2532 }
2533 }
2534
Dianne Hackborn41203752012-08-31 14:05:51 -07002535 final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002536 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002537 String resultWho, int requestCode, int startFlags, Bundle options, int userId) {
2538
2539 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2540 false, true, "startActivityInPackage", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541
Amith Yamasani742a6712011-05-04 14:49:28 -07002542 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002543 resultTo, resultWho, requestCode, startFlags,
Dianne Hackborn41203752012-08-31 14:05:51 -07002544 null, null, null, null, options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002545 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002546 }
2547
2548 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002549 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002550 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002551 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002552 options, UserHandle.getCallingUserId());
Amith Yamasani742a6712011-05-04 14:49:28 -07002553 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002554 }
2555
Dianne Hackborn41203752012-08-31 14:05:51 -07002556 final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002557 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002558 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002559
Dianne Hackborn41203752012-08-31 14:05:51 -07002560 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2561 false, true, "startActivityInPackage", null);
Amith Yamasani742a6712011-05-04 14:49:28 -07002562 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackborn41203752012-08-31 14:05:51 -07002563 options, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07002564 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 }
2566
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002567 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002569 // Quick case: check if the top-most recent task is the same.
2570 if (N > 0 && mRecentTasks.get(0) == task) {
2571 return;
2572 }
2573 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 for (int i=0; i<N; i++) {
2575 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002576 if (task.userId == tr.userId
2577 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2578 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 mRecentTasks.remove(i);
2580 i--;
2581 N--;
2582 if (task.intent == null) {
2583 // If the new recent task we are adding is not fully
2584 // specified, then replace it with the existing recent task.
2585 task = tr;
2586 }
2587 }
2588 }
2589 if (N >= MAX_RECENT_TASKS) {
2590 mRecentTasks.remove(N-1);
2591 }
2592 mRecentTasks.add(0, task);
2593 }
2594
2595 public void setRequestedOrientation(IBinder token,
2596 int requestedOrientation) {
2597 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002598 ActivityRecord r = mMainStack.isInStackLocked(token);
2599 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 return;
2601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002603 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002605 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002606 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 if (config != null) {
2608 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002609 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002610 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 }
2612 }
2613 Binder.restoreCallingIdentity(origId);
2614 }
2615 }
2616
2617 public int getRequestedOrientation(IBinder token) {
2618 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002619 ActivityRecord r = mMainStack.isInStackLocked(token);
2620 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2622 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002623 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 }
2625 }
2626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 /**
2628 * This is the internal entry point for handling Activity.finish().
2629 *
2630 * @param token The Binder token referencing the Activity we want to finish.
2631 * @param resultCode Result code, if any, from this Activity.
2632 * @param resultData Result data (Intent), if any, from this Activity.
2633 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002634 * @return Returns true if the activity successfully finished, or false if it is still running.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002635 */
2636 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2637 // Refuse possible leaked file descriptors
2638 if (resultData != null && resultData.hasFileDescriptors() == true) {
2639 throw new IllegalArgumentException("File descriptors passed in Intent");
2640 }
2641
2642 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002643 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002645 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 if (next != null) {
2647 // ask watcher if this is allowed
2648 boolean resumeOK = true;
2649 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002650 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002652 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 }
2654
2655 if (!resumeOK) {
2656 return false;
2657 }
2658 }
2659 }
2660 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002661 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 resultData, "app-request");
2663 Binder.restoreCallingIdentity(origId);
2664 return res;
2665 }
2666 }
2667
Dianne Hackborn860755f2010-06-03 18:47:52 -07002668 public final void finishHeavyWeightApp() {
2669 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2670 != PackageManager.PERMISSION_GRANTED) {
2671 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2672 + Binder.getCallingPid()
2673 + ", uid=" + Binder.getCallingUid()
2674 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2675 Slog.w(TAG, msg);
2676 throw new SecurityException(msg);
2677 }
2678
2679 synchronized(this) {
2680 if (mHeavyWeightProcess == null) {
2681 return;
2682 }
2683
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002684 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002685 mHeavyWeightProcess.activities);
2686 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002687 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002688 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002689 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002690 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002691 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002692 null, "finish-heavy");
2693 }
2694 }
2695 }
2696
Dianne Hackborn41203752012-08-31 14:05:51 -07002697 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
2698 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07002699 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07002700 }
2701 }
2702
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002703 public void crashApplication(int uid, int initialPid, String packageName,
2704 String message) {
2705 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2706 != PackageManager.PERMISSION_GRANTED) {
2707 String msg = "Permission Denial: crashApplication() from pid="
2708 + Binder.getCallingPid()
2709 + ", uid=" + Binder.getCallingUid()
2710 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2711 Slog.w(TAG, msg);
2712 throw new SecurityException(msg);
2713 }
2714
2715 synchronized(this) {
2716 ProcessRecord proc = null;
2717
2718 // Figure out which process to kill. We don't trust that initialPid
2719 // still has any relation to current pids, so must scan through the
2720 // list.
2721 synchronized (mPidsSelfLocked) {
2722 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2723 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002724 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002725 continue;
2726 }
2727 if (p.pid == initialPid) {
2728 proc = p;
2729 break;
2730 }
2731 for (String str : p.pkgList) {
2732 if (str.equals(packageName)) {
2733 proc = p;
2734 }
2735 }
2736 }
2737 }
2738
2739 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002740 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002741 + " initialPid=" + initialPid
2742 + " packageName=" + packageName);
2743 return;
2744 }
2745
2746 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002747 if (proc.pid == Process.myPid()) {
2748 Log.w(TAG, "crashApplication: trying to crash self!");
2749 return;
2750 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002751 long ident = Binder.clearCallingIdentity();
2752 try {
2753 proc.thread.scheduleCrash(message);
2754 } catch (RemoteException e) {
2755 }
2756 Binder.restoreCallingIdentity(ident);
2757 }
2758 }
2759 }
2760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002761 public final void finishSubActivity(IBinder token, String resultWho,
2762 int requestCode) {
2763 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002764 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002765 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 Binder.restoreCallingIdentity(origId);
2767 }
2768 }
2769
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002770 public boolean finishActivityAffinity(IBinder token) {
2771 synchronized(this) {
2772 final long origId = Binder.clearCallingIdentity();
2773 boolean res = mMainStack.finishActivityAffinityLocked(token);
2774 Binder.restoreCallingIdentity(origId);
2775 return res;
2776 }
2777 }
2778
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002779 public boolean willActivityBeVisible(IBinder token) {
2780 synchronized(this) {
2781 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002782 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2783 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002784 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002785 return true;
2786 }
2787 if (r.fullscreen && !r.finishing) {
2788 return false;
2789 }
2790 }
2791 return true;
2792 }
2793 }
2794
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002795 public void overridePendingTransition(IBinder token, String packageName,
2796 int enterAnim, int exitAnim) {
2797 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002798 ActivityRecord self = mMainStack.isInStackLocked(token);
2799 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002800 return;
2801 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002802
2803 final long origId = Binder.clearCallingIdentity();
2804
2805 if (self.state == ActivityState.RESUMED
2806 || self.state == ActivityState.PAUSING) {
2807 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002808 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002809 }
2810
2811 Binder.restoreCallingIdentity(origId);
2812 }
2813 }
2814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 * Main function for removing an existing process from the activity manager
2817 * as a result of that process going away. Clears out all connections
2818 * to the process.
2819 */
2820 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002821 boolean restarting, boolean allowRestart) {
2822 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002824 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 }
2826
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002827 if (mProfileProc == app) {
2828 clearProfilerLocked();
2829 }
2830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002832 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2833 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2834 mMainStack.mPausingActivity = null;
2835 }
2836 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2837 mMainStack.mLastPausedActivity = null;
2838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839
2840 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002841 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002842
2843 boolean atTop = true;
2844 boolean hasVisibleActivities = false;
2845
2846 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002847 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002848 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849 TAG, "Removing app " + app + " from history with " + i + " entries");
2850 while (i > 0) {
2851 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002852 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002853 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2855 if (r.app == app) {
2856 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002857 if (ActivityStack.DEBUG_ADD_REMOVE) {
2858 RuntimeException here = new RuntimeException("here");
2859 here.fillInStackTrace();
2860 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2861 + ": haveState=" + r.haveState
2862 + " stateNotNeeded=" + r.stateNotNeeded
2863 + " finishing=" + r.finishing
2864 + " state=" + r.state, here);
2865 }
2866 if (!r.finishing) {
2867 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002868 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2869 System.identityHashCode(r),
2870 r.task.taskId, r.shortComponentName,
2871 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002872 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002873 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874
2875 } else {
2876 // We have the current state for this activity, so
2877 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002878 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 TAG, "Keeping entry, setting app to null");
2880 if (r.visible) {
2881 hasVisibleActivities = true;
2882 }
2883 r.app = null;
2884 r.nowVisible = false;
2885 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002886 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2887 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 r.icicle = null;
2889 }
2890 }
2891
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002892 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 }
2894 atTop = false;
2895 }
2896
2897 app.activities.clear();
2898
2899 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002900 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 + " running instrumentation " + app.instrumentationClass);
2902 Bundle info = new Bundle();
2903 info.putString("shortMsg", "Process crashed.");
2904 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2905 }
2906
2907 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002908 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 // If there was nothing to resume, and we are not already
2910 // restarting this process, but there is a visible activity that
2911 // is hosted by the process... then make sure all visible
2912 // activities are running, taking care of restarting this
2913 // process.
2914 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002915 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 }
2917 }
2918 }
2919 }
2920
2921 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2922 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002924 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2925 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002926 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2927 return i;
2928 }
2929 }
2930 return -1;
2931 }
2932
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002933 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 IApplicationThread thread) {
2935 if (thread == null) {
2936 return null;
2937 }
2938
2939 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002940 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 }
2942
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002943 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 IApplicationThread thread) {
2945
2946 mProcDeaths[0]++;
2947
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002948 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2949 synchronized (stats) {
2950 stats.noteProcessDiedLocked(app.info.uid, pid);
2951 }
2952
Magnus Edlund7bb25812010-02-24 15:45:06 +01002953 // Clean up already done if the process has been re-started.
2954 if (app.pid == pid && app.thread != null &&
2955 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002956 if (!app.killedBackground) {
2957 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2958 + ") has died.");
2959 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002960 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002961 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 TAG, "Dying app: " + app + ", pid: " + pid
2963 + ", thread: " + thread.asBinder());
2964 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002965 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966
2967 if (doLowMem) {
2968 // If there are no longer any background processes running,
2969 // and the app that died was not running instrumentation,
2970 // then tell everyone we are now low on memory.
2971 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002972 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2973 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002974 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 haveBg = true;
2976 break;
2977 }
2978 }
2979
2980 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002981 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002982 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002983 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2984 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002985 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002986 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
2987 // The low memory report is overriding any current
2988 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07002989 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07002990 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002991 rec.lastRequestedGc = 0;
2992 } else {
2993 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002995 rec.reportLowMemory = true;
2996 rec.lastLowMemory = now;
2997 mProcessesToGc.remove(rec);
2998 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 }
3000 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003001 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003002 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003 }
3004 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003005 } else if (app.pid != pid) {
3006 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003007 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003008 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003009 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003010 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003011 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003012 + thread.asBinder());
3013 }
3014 }
3015
Dan Egnor42471dd2010-01-07 17:25:22 -08003016 /**
3017 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003018 * @param clearTraces causes the dump file to be erased prior to the new
3019 * traces being written, if true; when false, the new traces will be
3020 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003021 * @param firstPids of dalvik VM processes to dump stack traces for first
3022 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003023 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003024 * @return file containing stack traces, or null if no dump file is configured
3025 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003026 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003027 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003028 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3029 if (tracesPath == null || tracesPath.length() == 0) {
3030 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003032
3033 File tracesFile = new File(tracesPath);
3034 try {
3035 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003036 if (!tracesDir.exists()) {
3037 tracesFile.mkdirs();
3038 if (!SELinux.restorecon(tracesDir)) {
3039 return null;
3040 }
3041 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003042 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3043
Christopher Tate6ee412d2010-05-28 12:01:56 -07003044 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003045 tracesFile.createNewFile();
3046 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3047 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003048 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003049 return null;
3050 }
3051
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003052 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003053 return tracesFile;
3054 }
3055
3056 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003057 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003058 // Use a FileObserver to detect when traces finish writing.
3059 // The order of traces is considered important to maintain for legibility.
3060 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3061 public synchronized void onEvent(int event, String path) { notify(); }
3062 };
3063
3064 try {
3065 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003066
3067 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003068 if (firstPids != null) {
3069 try {
3070 int num = firstPids.size();
3071 for (int i = 0; i < num; i++) {
3072 synchronized (observer) {
3073 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3074 observer.wait(200); // Wait for write-close, give up after 200msec
3075 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003076 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003077 } catch (InterruptedException e) {
3078 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003079 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003080 }
3081
3082 // Next measure CPU usage.
3083 if (processStats != null) {
3084 processStats.init();
3085 System.gc();
3086 processStats.update();
3087 try {
3088 synchronized (processStats) {
3089 processStats.wait(500); // measure over 1/2 second.
3090 }
3091 } catch (InterruptedException e) {
3092 }
3093 processStats.update();
3094
3095 // We'll take the stack crawls of just the top apps using CPU.
3096 final int N = processStats.countWorkingStats();
3097 int numProcs = 0;
3098 for (int i=0; i<N && numProcs<5; i++) {
3099 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3100 if (lastPids.indexOfKey(stats.pid) >= 0) {
3101 numProcs++;
3102 try {
3103 synchronized (observer) {
3104 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3105 observer.wait(200); // Wait for write-close, give up after 200msec
3106 }
3107 } catch (InterruptedException e) {
3108 Log.wtf(TAG, e);
3109 }
3110
3111 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003112 }
3113 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003114
Dan Egnor42471dd2010-01-07 17:25:22 -08003115 } finally {
3116 observer.stopWatching();
3117 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003118
3119 if (nativeProcs != null) {
3120 int[] pids = Process.getPidsForCommands(nativeProcs);
3121 if (pids != null) {
3122 for (int pid : pids) {
3123 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3124 }
3125 }
3126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 }
3128
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003129 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003130 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003131 return;
3132 }
3133 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3134 if (tracesPath == null || tracesPath.length() == 0) {
3135 return;
3136 }
3137
3138 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3139 StrictMode.allowThreadDiskWrites();
3140 try {
3141 final File tracesFile = new File(tracesPath);
3142 final File tracesDir = tracesFile.getParentFile();
3143 final File tracesTmp = new File(tracesDir, "__tmp__");
3144 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003145 if (!tracesDir.exists()) {
3146 tracesFile.mkdirs();
3147 if (!SELinux.restorecon(tracesDir.getPath())) {
3148 return;
3149 }
3150 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003151 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3152
3153 if (tracesFile.exists()) {
3154 tracesTmp.delete();
3155 tracesFile.renameTo(tracesTmp);
3156 }
3157 StringBuilder sb = new StringBuilder();
3158 Time tobj = new Time();
3159 tobj.set(System.currentTimeMillis());
3160 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3161 sb.append(": ");
3162 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3163 sb.append(" since ");
3164 sb.append(msg);
3165 FileOutputStream fos = new FileOutputStream(tracesFile);
3166 fos.write(sb.toString().getBytes());
3167 if (app == null) {
3168 fos.write("\n*** No application process!".getBytes());
3169 }
3170 fos.close();
3171 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3172 } catch (IOException e) {
3173 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3174 return;
3175 }
3176
3177 if (app != null) {
3178 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3179 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003180 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003181 }
3182
3183 File lastTracesFile = null;
3184 File curTracesFile = null;
3185 for (int i=9; i>=0; i--) {
3186 String name = String.format("slow%02d.txt", i);
3187 curTracesFile = new File(tracesDir, name);
3188 if (curTracesFile.exists()) {
3189 if (lastTracesFile != null) {
3190 curTracesFile.renameTo(lastTracesFile);
3191 } else {
3192 curTracesFile.delete();
3193 }
3194 }
3195 lastTracesFile = curTracesFile;
3196 }
3197 tracesFile.renameTo(curTracesFile);
3198 if (tracesTmp.exists()) {
3199 tracesTmp.renameTo(tracesFile);
3200 }
3201 } finally {
3202 StrictMode.setThreadPolicy(oldPolicy);
3203 }
3204 }
3205
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003206 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3207 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003208 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3209 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3210
Dianne Hackborn287952c2010-09-22 22:34:31 -07003211 if (mController != null) {
3212 try {
3213 // 0 == continue, -1 = kill process immediately
3214 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3215 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3216 } catch (RemoteException e) {
3217 mController = null;
3218 }
3219 }
3220
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003221 long anrTime = SystemClock.uptimeMillis();
3222 if (MONITOR_CPU_USAGE) {
3223 updateCpuStatsNow();
3224 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003225
3226 synchronized (this) {
3227 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3228 if (mShuttingDown) {
3229 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3230 return;
3231 } else if (app.notResponding) {
3232 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3233 return;
3234 } else if (app.crashing) {
3235 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3236 return;
3237 }
3238
3239 // In case we come through here for the same app before completing
3240 // this one, mark as anring now so we will bail out.
3241 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003242
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003243 // Log the ANR to the event log.
3244 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3245 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003246
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003247 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003248 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003249
3250 int parentPid = app.pid;
3251 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003252 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003253
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003254 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003255
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003256 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3257 ProcessRecord r = mLruProcesses.get(i);
3258 if (r != null && r.thread != null) {
3259 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003260 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3261 if (r.persistent) {
3262 firstPids.add(pid);
3263 } else {
3264 lastPids.put(pid, Boolean.TRUE);
3265 }
3266 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 }
3269 }
3270
Dan Egnor42471dd2010-01-07 17:25:22 -08003271 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003272 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003273 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003274 info.append("ANR in ").append(app.processName);
3275 if (activity != null && activity.shortComponentName != null) {
3276 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003277 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003278 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003280 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003282 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003283 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285
Dianne Hackborn287952c2010-09-22 22:34:31 -07003286 final ProcessStats processStats = new ProcessStats(true);
3287
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003288 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003289
Dan Egnor42471dd2010-01-07 17:25:22 -08003290 String cpuInfo = null;
3291 if (MONITOR_CPU_USAGE) {
3292 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003293 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003294 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003295 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003296 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003297 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 }
3299
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003300 info.append(processStats.printCurrentState(anrTime));
3301
Joe Onorato8a9b2202010-02-26 18:56:32 -08003302 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003303 if (tracesFile == null) {
3304 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3305 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3306 }
3307
Jeff Sharkeya353d262011-10-28 11:12:06 -07003308 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3309 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003310
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003311 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003313 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3314 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003316 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3317 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 }
3319 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003320 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 }
3322 }
3323
Dan Egnor42471dd2010-01-07 17:25:22 -08003324 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3325 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3326 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003327
3328 synchronized (this) {
3329 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003330 Slog.w(TAG, "Killing " + app + ": background ANR");
3331 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3332 app.processName, app.setAdj, "background ANR");
3333 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003334 return;
3335 }
3336
3337 // Set the app's notResponding state, and look up the errorReportReceiver
3338 makeAppNotRespondingLocked(app,
3339 activity != null ? activity.shortComponentName : null,
3340 annotation != null ? "ANR " + annotation : "ANR",
3341 info.toString());
3342
3343 // Bring up the infamous App Not Responding dialog
3344 Message msg = Message.obtain();
3345 HashMap map = new HashMap();
3346 msg.what = SHOW_NOT_RESPONDING_MSG;
3347 msg.obj = map;
3348 map.put("app", app);
3349 if (activity != null) {
3350 map.put("activity", activity);
3351 }
3352
3353 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 }
3356
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003357 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3358 if (!mLaunchWarningShown) {
3359 mLaunchWarningShown = true;
3360 mHandler.post(new Runnable() {
3361 @Override
3362 public void run() {
3363 synchronized (ActivityManagerService.this) {
3364 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3365 d.show();
3366 mHandler.postDelayed(new Runnable() {
3367 @Override
3368 public void run() {
3369 synchronized (ActivityManagerService.this) {
3370 d.dismiss();
3371 mLaunchWarningShown = false;
3372 }
3373 }
3374 }, 4000);
3375 }
3376 }
3377 });
3378 }
3379 }
3380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003382 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003383 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 int uid = Binder.getCallingUid();
3385 int pid = Binder.getCallingPid();
3386 long callingId = Binder.clearCallingIdentity();
3387 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003388 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 int pkgUid = -1;
3390 synchronized(this) {
3391 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003392 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 } catch (RemoteException e) {
3394 }
3395 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003396 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 return false;
3398 }
3399 if (uid == pkgUid || checkComponentPermission(
3400 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003401 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003403 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003404 } else {
3405 throw new SecurityException(pid+" does not have permission:"+
3406 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3407 "for process:"+packageName);
3408 }
3409 }
3410
3411 try {
3412 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003413 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003414 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3415 Uri.fromParts("package", packageName, null));
3416 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003417 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003418 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 } catch (RemoteException e) {
3420 }
3421 } finally {
3422 Binder.restoreCallingIdentity(callingId);
3423 }
3424 return true;
3425 }
3426
Dianne Hackborn03abb812010-01-04 18:43:19 -08003427 public void killBackgroundProcesses(final String packageName) {
3428 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3429 != PackageManager.PERMISSION_GRANTED &&
3430 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3431 != PackageManager.PERMISSION_GRANTED) {
3432 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 + Binder.getCallingPid()
3434 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003435 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003436 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 throw new SecurityException(msg);
3438 }
3439
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003440 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003441 long callingId = Binder.clearCallingIdentity();
3442 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003443 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003444 int pkgUid = -1;
3445 synchronized(this) {
3446 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003447 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003448 } catch (RemoteException e) {
3449 }
3450 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003451 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003452 return;
3453 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003454 killPackageProcessesLocked(packageName, pkgUid, -1,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003455 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3456 }
3457 } finally {
3458 Binder.restoreCallingIdentity(callingId);
3459 }
3460 }
3461
3462 public void killAllBackgroundProcesses() {
3463 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3464 != PackageManager.PERMISSION_GRANTED) {
3465 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3466 + Binder.getCallingPid()
3467 + ", uid=" + Binder.getCallingUid()
3468 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3469 Slog.w(TAG, msg);
3470 throw new SecurityException(msg);
3471 }
3472
3473 long callingId = Binder.clearCallingIdentity();
3474 try {
3475 synchronized(this) {
3476 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3477 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3478 final int NA = apps.size();
3479 for (int ia=0; ia<NA; ia++) {
3480 ProcessRecord app = apps.valueAt(ia);
3481 if (app.persistent) {
3482 // we don't kill persistent processes
3483 continue;
3484 }
3485 if (app.removed) {
3486 procs.add(app);
3487 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3488 app.removed = true;
3489 procs.add(app);
3490 }
3491 }
3492 }
3493
3494 int N = procs.size();
3495 for (int i=0; i<N; i++) {
3496 removeProcessLocked(procs.get(i), false, true, "kill all background");
3497 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003498 }
3499 } finally {
3500 Binder.restoreCallingIdentity(callingId);
3501 }
3502 }
3503
3504 public void forceStopPackage(final String packageName) {
3505 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3506 != PackageManager.PERMISSION_GRANTED) {
3507 String msg = "Permission Denial: forceStopPackage() from pid="
3508 + Binder.getCallingPid()
3509 + ", uid=" + Binder.getCallingUid()
3510 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003511 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003512 throw new SecurityException(msg);
3513 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003514 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003515 long callingId = Binder.clearCallingIdentity();
3516 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003517 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003518 int pkgUid = -1;
3519 synchronized(this) {
3520 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003521 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003522 } catch (RemoteException e) {
3523 }
3524 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003525 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003526 return;
3527 }
3528 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003529 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003530 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003531 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003532 } catch (IllegalArgumentException e) {
3533 Slog.w(TAG, "Failed trying to unstop package "
3534 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003536 }
3537 } finally {
3538 Binder.restoreCallingIdentity(callingId);
3539 }
3540 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003541
3542 /*
3543 * The pkg name and uid have to be specified.
3544 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3545 */
3546 public void killApplicationWithUid(String pkg, int uid) {
3547 if (pkg == null) {
3548 return;
3549 }
3550 // Make sure the uid is valid.
3551 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003552 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003553 return;
3554 }
3555 int callerUid = Binder.getCallingUid();
3556 // Only the system server can kill an application
3557 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003558 // Post an aysnc message to kill the application
3559 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3560 msg.arg1 = uid;
3561 msg.arg2 = 0;
3562 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003563 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003564 } else {
3565 throw new SecurityException(callerUid + " cannot kill pkg: " +
3566 pkg);
3567 }
3568 }
3569
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003570 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003571 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003572
3573 final int uid = Binder.getCallingUid();
3574 final long origId = Binder.clearCallingIdentity();
3575 synchronized (this) {
3576 closeSystemDialogsLocked(uid, reason);
3577 }
3578 Binder.restoreCallingIdentity(origId);
3579 }
3580
3581 void closeSystemDialogsLocked(int callingUid, String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003582 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003583 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003584 if (reason != null) {
3585 intent.putExtra("reason", reason);
3586 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003587 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003588
Dianne Hackborne302a162012-05-15 14:58:32 -07003589 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3590 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003591 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003592 r.stack.finishActivityLocked(r, i,
3593 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003594 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003595 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003596
3597 final long origId = Binder.clearCallingIdentity();
3598 try {
3599 broadcastIntentLocked(null, null, intent, null,
3600 null, 0, null, null, null, false, false, -1,
3601 callingUid, UserHandle.USER_ALL);
3602 } finally {
3603 Binder.restoreCallingIdentity(origId);
3604 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003605 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003606
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003607 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003608 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003609 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003610 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3611 for (int i=pids.length-1; i>=0; i--) {
3612 infos[i] = new Debug.MemoryInfo();
3613 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003614 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003615 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003616 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003617
Dianne Hackbornb437e092011-08-05 17:50:29 -07003618 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003619 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003620 long[] pss = new long[pids.length];
3621 for (int i=pids.length-1; i>=0; i--) {
3622 pss[i] = Debug.getPss(pids[i]);
3623 }
3624 return pss;
3625 }
3626
Christopher Tate5e1ab332009-09-01 20:32:49 -07003627 public void killApplicationProcess(String processName, int uid) {
3628 if (processName == null) {
3629 return;
3630 }
3631
3632 int callerUid = Binder.getCallingUid();
3633 // Only the system server can kill an application
3634 if (callerUid == Process.SYSTEM_UID) {
3635 synchronized (this) {
3636 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003637 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003638 try {
3639 app.thread.scheduleSuicide();
3640 } catch (RemoteException e) {
3641 // If the other end already died, then our work here is done.
3642 }
3643 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003644 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003645 + processName + " / " + uid);
3646 }
3647 }
3648 } else {
3649 throw new SecurityException(callerUid + " cannot kill app process: " +
3650 processName);
3651 }
3652 }
3653
Dianne Hackborn03abb812010-01-04 18:43:19 -08003654 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003655 forceStopPackageLocked(packageName, uid, false, false, true, false,
3656 UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003657 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3658 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003659 if (!mProcessesReady) {
3660 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 intent.putExtra(Intent.EXTRA_UID, uid);
3663 broadcastIntentLocked(null, null, intent,
3664 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003665 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003666 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003668
3669 private void forceStopUserLocked(int userId) {
3670 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3671 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
3672 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3673 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3674 broadcastIntentLocked(null, null, intent,
3675 null, null, 0, null, null, null,
3676 false, false,
3677 MY_PID, Process.SYSTEM_UID, userId);
3678 }
3679
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003680 private final boolean killPackageProcessesLocked(String packageName, int uid,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003681 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3682 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003683 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684
Dianne Hackborn03abb812010-01-04 18:43:19 -08003685 // Remove all processes this package may have touched: all with the
3686 // same UID (except for the system or root user), and all whose name
3687 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003688 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003689 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3690 final int NA = apps.size();
3691 for (int ia=0; ia<NA; ia++) {
3692 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003693 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003694 // we don't kill persistent processes
3695 continue;
3696 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003697 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003698 if (doit) {
3699 procs.add(app);
3700 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003701 // If no package is specified, we call all processes under the
3702 // give user id.
3703 } else if (packageName == null) {
3704 if (app.userId == userId) {
3705 if (app.setAdj >= minOomAdj) {
3706 if (!doit) {
3707 return true;
3708 }
3709 app.removed = true;
3710 procs.add(app);
3711 }
3712 }
Amith Yamasani13593602012-03-22 16:16:17 -07003713 // If uid is specified and the uid and process name match
3714 // Or, the uid is not specified and the process name matches
3715 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003716 || ((app.processName.equals(packageName)
3717 || app.processName.startsWith(procNamePrefix))
3718 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003719 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003720 if (!doit) {
3721 return true;
3722 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003723 app.removed = true;
3724 procs.add(app);
3725 }
3726 }
3727 }
3728 }
3729
3730 int N = procs.size();
3731 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003732 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003733 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003734 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003735 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003736
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003737 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003738 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003739 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003740 int i;
3741 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003742
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003743 if (uid < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003745 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 } catch (RemoteException e) {
3747 }
3748 }
3749
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003750 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003751 if (name != null) {
3752 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
3753 } else {
3754 Slog.i(TAG, "Force stopping user " + userId);
3755 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003756
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003757 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3758 while (badApps.hasNext()) {
3759 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003760 for (i=ba.size()-1; i>=0; i--) {
3761 boolean remove = false;
3762 final int entUid = ba.keyAt(i);
3763 if (name != null) {
3764 if (entUid == uid) {
3765 remove = true;
3766 }
3767 } else if (UserHandle.getUserId(entUid) == userId) {
3768 remove = true;
3769 }
3770 if (remove) {
3771 ba.removeAt(i);
3772 }
3773 }
3774 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003775 badApps.remove();
3776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777 }
3778 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003779
3780 boolean didSomething = killPackageProcessesLocked(name, uid,
3781 name == null ? userId : -1 , -100, callerWillRestart, false,
3782 doit, evenPersistent,
3783 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003785 TaskRecord lastTask = null;
3786 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003787 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003788 final boolean samePackage = r.packageName.equals(name)
3789 || (name == null && r.userId == userId);
Amith Yamasani13593602012-03-22 16:16:17 -07003790 if (r.userId == userId
3791 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003792 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003793 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003794 if (r.finishing) {
3795 // If this activity is just finishing, then it is not
3796 // interesting as far as something to stop.
3797 continue;
3798 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003799 return true;
3800 }
3801 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003802 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003803 if (samePackage) {
3804 if (r.app != null) {
3805 r.app.removed = true;
3806 }
3807 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003809 lastTask = r.task;
3810 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003811 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003812 i--;
3813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003814 }
3815 }
3816
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003817 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3818 if (!doit) {
3819 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003821 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003823
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003824 if (name == null) {
3825 // Remove all sticky broadcasts from this user.
3826 mStickyBroadcasts.remove(userId);
3827 }
3828
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003829 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003830 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003831 if ((name == null || provider.info.packageName.equals(name))
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003832 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3833 if (!doit) {
3834 return true;
3835 }
3836 didSomething = true;
3837 providers.add(provider);
3838 }
3839 }
3840
3841 N = providers.size();
3842 for (i=0; i<N; i++) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003843 removeDyingProviderLocked(null, providers.get(i), true);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003844 }
3845
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003846 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003847 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003848 AttributeCache ac = AttributeCache.instance();
3849 if (ac != null) {
3850 ac.removePackage(name);
3851 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003852 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003853 if (mBooted) {
3854 mMainStack.resumeTopActivityLocked(null);
3855 mMainStack.scheduleIdleLocked();
3856 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003857 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003858
3859 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 }
3861
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003862 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003863 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003865 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003866 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003867 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 + "/" + uid + ")");
3869
3870 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003871 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003872 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07003873 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
3874 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07003875 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 boolean needRestart = false;
3878 if (app.pid > 0 && app.pid != MY_PID) {
3879 int pid = app.pid;
3880 synchronized (mPidsSelfLocked) {
3881 mPidsSelfLocked.remove(pid);
3882 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3883 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003884 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003885 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003886 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003887 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003889 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003891 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 } else {
3893 needRestart = true;
3894 }
3895 }
3896 } else {
3897 mRemovedProcesses.add(app);
3898 }
3899
3900 return needRestart;
3901 }
3902
3903 private final void processStartTimedOutLocked(ProcessRecord app) {
3904 final int pid = app.pid;
3905 boolean gone = false;
3906 synchronized (mPidsSelfLocked) {
3907 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3908 if (knownApp != null && knownApp.thread == null) {
3909 mPidsSelfLocked.remove(pid);
3910 gone = true;
3911 }
3912 }
3913
3914 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003915 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003916 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003917 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003918 mProcessNames.remove(app.processName, app.uid);
3919 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003920 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -07003921 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
3922 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -07003923 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -07003924 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003925 // Take care of any launching providers waiting for this process.
3926 checkAppInLaunchingProvidersLocked(app, true);
3927 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003928 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003929 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3930 app.processName, app.setAdj, "start timeout");
3931 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003932 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003933 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003934 try {
3935 IBackupManager bm = IBackupManager.Stub.asInterface(
3936 ServiceManager.getService(Context.BACKUP_SERVICE));
3937 bm.agentDisconnected(app.info.packageName);
3938 } catch (RemoteException e) {
3939 // Can't happen; the backup manager is local
3940 }
3941 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003942 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003943 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003944 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003946 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003947 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 }
3949 }
3950
3951 private final boolean attachApplicationLocked(IApplicationThread thread,
3952 int pid) {
3953
3954 // Find the application record that is being attached... either via
3955 // the pid if we are running in multiple processes, or just pull the
3956 // next app record if we are emulating process with anonymous threads.
3957 ProcessRecord app;
3958 if (pid != MY_PID && pid >= 0) {
3959 synchronized (mPidsSelfLocked) {
3960 app = mPidsSelfLocked.get(pid);
3961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 } else {
3963 app = null;
3964 }
3965
3966 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003967 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003969 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003971 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003972 } else {
3973 try {
3974 thread.scheduleExit();
3975 } catch (Exception e) {
3976 // Ignore exceptions.
3977 }
3978 }
3979 return false;
3980 }
3981
3982 // If this application record is still attached to a previous
3983 // process, clean it up now.
3984 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003985 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 }
3987
3988 // Tell the process all about itself.
3989
Joe Onorato8a9b2202010-02-26 18:56:32 -08003990 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 TAG, "Binding process pid " + pid + " to record " + app);
3992
3993 String processName = app.processName;
3994 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07003995 AppDeathRecipient adr = new AppDeathRecipient(
3996 app, pid, thread);
3997 thread.asBinder().linkToDeath(adr, 0);
3998 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 } catch (RemoteException e) {
4000 app.resetPackageList();
4001 startProcessLocked(app, "link fail", processName);
4002 return false;
4003 }
4004
Doug Zongker2bec3d42009-12-04 12:52:44 -08004005 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006
4007 app.thread = thread;
4008 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004009 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4010 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 app.forcingToForeground = null;
4012 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004013 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 app.debugging = false;
4015
4016 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4017
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004018 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004019 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004021 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004022 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004023 }
4024
Joe Onorato8a9b2202010-02-26 18:56:32 -08004025 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 TAG, "New app record " + app
4027 + " thread=" + thread.asBinder() + " pid=" + pid);
4028 try {
4029 int testMode = IApplicationThread.DEBUG_OFF;
4030 if (mDebugApp != null && mDebugApp.equals(processName)) {
4031 testMode = mWaitForDebugger
4032 ? IApplicationThread.DEBUG_WAIT
4033 : IApplicationThread.DEBUG_ON;
4034 app.debugging = true;
4035 if (mDebugTransient) {
4036 mDebugApp = mOrigDebugApp;
4037 mWaitForDebugger = mOrigWaitForDebugger;
4038 }
4039 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004040 String profileFile = app.instrumentationProfileFile;
4041 ParcelFileDescriptor profileFd = null;
4042 boolean profileAutoStop = false;
4043 if (mProfileApp != null && mProfileApp.equals(processName)) {
4044 mProfileProc = app;
4045 profileFile = mProfileFile;
4046 profileFd = mProfileFd;
4047 profileAutoStop = mAutoStopProfiler;
4048 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004049 boolean enableOpenGlTrace = false;
4050 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4051 enableOpenGlTrace = true;
4052 mOpenGlTraceApp = null;
4053 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004054
Christopher Tate181fafa2009-05-14 11:12:14 -07004055 // If the app is being launched for restore or full backup, set it up specially
4056 boolean isRestrictedBackupMode = false;
4057 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4058 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004059 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004060 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4061 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004062
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004063 ensurePackageDexOpt(app.instrumentationInfo != null
4064 ? app.instrumentationInfo.packageName
4065 : app.info.packageName);
4066 if (app.instrumentationClass != null) {
4067 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004068 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004069 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004070 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004071 ApplicationInfo appInfo = app.instrumentationInfo != null
4072 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004073 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004074 if (profileFd != null) {
4075 profileFd = profileFd.dup();
4076 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004077 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004078 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004079 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4080 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004081 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004082 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004083 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004084 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 } catch (Exception e) {
4086 // todo: Yikes! What should we do? For now we will try to
4087 // start another process, but that could easily get us in
4088 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004089 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090
4091 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004092 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 startProcessLocked(app, "bind fail", processName);
4094 return false;
4095 }
4096
4097 // Remove this record from the list of starting applications.
4098 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004099 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4100 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004101 mProcessesOnHold.remove(app);
4102
4103 boolean badApp = false;
4104 boolean didSomething = false;
4105
4106 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004107 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004108 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004109 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 && processName.equals(hr.processName)) {
4111 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004112 if (mHeadless) {
4113 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4114 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 didSomething = true;
4116 }
4117 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004118 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 + hr.intent.getComponent().flattenToShortString(), e);
4120 badApp = true;
4121 }
4122 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004123 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 }
4125 }
4126
4127 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004128 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004129 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004130 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 badApp = true;
4133 }
4134 }
4135
Christopher Tatef46723b2012-01-26 14:19:24 -08004136 // Check if a next-broadcast receiver is in this process...
4137 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004139 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004141 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004142 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 }
4144 }
4145
Christopher Tate181fafa2009-05-14 11:12:14 -07004146 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004147 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004148 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004149 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004150 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004151 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4152 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4153 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004154 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004155 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004156 e.printStackTrace();
4157 }
4158 }
4159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 if (badApp) {
4161 // todo: Also need to kill application to deal with all
4162 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004163 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 return false;
4165 }
4166
4167 if (!didSomething) {
4168 updateOomAdjLocked();
4169 }
4170
4171 return true;
4172 }
4173
4174 public final void attachApplication(IApplicationThread thread) {
4175 synchronized (this) {
4176 int callingPid = Binder.getCallingPid();
4177 final long origId = Binder.clearCallingIdentity();
4178 attachApplicationLocked(thread, callingPid);
4179 Binder.restoreCallingIdentity(origId);
4180 }
4181 }
4182
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004183 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004185 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4186 if (stopProfiling) {
4187 synchronized (this) {
4188 if (mProfileProc == r.app) {
4189 if (mProfileFd != null) {
4190 try {
4191 mProfileFd.close();
4192 } catch (IOException e) {
4193 }
4194 clearProfilerLocked();
4195 }
4196 }
4197 }
4198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 Binder.restoreCallingIdentity(origId);
4200 }
4201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004203 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004204 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004206
4207 synchronized (this) {
4208 updateEventDispatchingLocked();
4209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004210 }
4211
Dianne Hackborn661cd522011-08-22 00:26:20 -07004212 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004213 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004214 mWindowManager.showBootMessage(msg, always);
4215 }
4216
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004217 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004218 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004219 final long token = Binder.clearCallingIdentity();
4220 try {
4221 synchronized (this) {
4222 if (mLockScreenShown) {
4223 mLockScreenShown = false;
4224 comeOutOfSleepIfNeededLocked();
4225 }
4226 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004227 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004228 } finally {
4229 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004230 }
4231 }
4232
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004233 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004234 IntentFilter pkgFilter = new IntentFilter();
4235 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4236 pkgFilter.addDataScheme("package");
4237 mContext.registerReceiver(new BroadcastReceiver() {
4238 @Override
4239 public void onReceive(Context context, Intent intent) {
4240 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4241 if (pkgs != null) {
4242 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004243 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004244 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4245 setResultCode(Activity.RESULT_OK);
4246 return;
4247 }
4248 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004249 }
4250 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004251 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004252 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004253
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004254 synchronized (this) {
4255 // Ensure that any processes we had put on hold are now started
4256 // up.
4257 final int NP = mProcessesOnHold.size();
4258 if (NP > 0) {
4259 ArrayList<ProcessRecord> procs =
4260 new ArrayList<ProcessRecord>(mProcessesOnHold);
4261 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004262 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4263 + procs.get(ip));
4264 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004265 }
4266 }
4267
4268 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004269 // Start looking for apps that are abusing wake locks.
4270 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004271 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004272 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004273 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004274 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004275 for (int i=0; i<mStartedUsers.size(); i++) {
4276 UserStartedState uss = mStartedUsers.valueAt(i);
4277 if (uss.mState == UserStartedState.STATE_BOOTING) {
4278 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -07004279 final int userId = mStartedUsers.keyAt(i);
4280 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
4281 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
4282 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004283 null, null, 0, null, null,
4284 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -07004285 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004286 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004287 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004288 }
4289 }
4290 }
4291
4292 final void ensureBootCompleted() {
4293 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004294 boolean enableScreen;
4295 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004296 booting = mBooting;
4297 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004298 enableScreen = !mBooted;
4299 mBooted = true;
4300 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004301
4302 if (booting) {
4303 finishBooting();
4304 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004305
4306 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004307 enableScreenAfterBoot();
4308 }
4309 }
4310
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004311 public final void activityPaused(IBinder token) {
4312 final long origId = Binder.clearCallingIdentity();
4313 mMainStack.activityPaused(token, false);
4314 Binder.restoreCallingIdentity(origId);
4315 }
4316
4317 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4318 CharSequence description) {
4319 if (localLOGV) Slog.v(
4320 TAG, "Activity stopped: token=" + token);
4321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004322 // Refuse possible leaked file descriptors
4323 if (icicle != null && icicle.hasFileDescriptors()) {
4324 throw new IllegalArgumentException("File descriptors passed in Bundle");
4325 }
4326
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004327 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004328
4329 final long origId = Binder.clearCallingIdentity();
4330
4331 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004332 r = mMainStack.isInStackLocked(token);
4333 if (r != null) {
4334 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004335 }
4336 }
4337
4338 if (r != null) {
4339 sendPendingThumbnail(r, null, null, null, false);
4340 }
4341
4342 trimApplications();
4343
4344 Binder.restoreCallingIdentity(origId);
4345 }
4346
4347 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004348 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004349 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004350 }
4351
4352 public String getCallingPackage(IBinder token) {
4353 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004354 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004355 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 }
4357 }
4358
4359 public ComponentName getCallingActivity(IBinder token) {
4360 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004361 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004362 return r != null ? r.intent.getComponent() : null;
4363 }
4364 }
4365
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004366 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004367 ActivityRecord r = mMainStack.isInStackLocked(token);
4368 if (r == null) {
4369 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004370 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004371 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 }
4373
4374 public ComponentName getActivityClassForToken(IBinder token) {
4375 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004376 ActivityRecord r = mMainStack.isInStackLocked(token);
4377 if (r == null) {
4378 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004379 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004380 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004381 }
4382 }
4383
4384 public String getPackageForToken(IBinder token) {
4385 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004386 ActivityRecord r = mMainStack.isInStackLocked(token);
4387 if (r == null) {
4388 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004389 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004390 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 }
4392 }
4393
4394 public IIntentSender getIntentSender(int type,
4395 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004396 int requestCode, Intent[] intents, String[] resolvedTypes,
Dianne Hackborn41203752012-08-31 14:05:51 -07004397 int flags, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004398 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004400 if (intents != null) {
4401 if (intents.length < 1) {
4402 throw new IllegalArgumentException("Intents array length must be >= 1");
4403 }
4404 for (int i=0; i<intents.length; i++) {
4405 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004406 if (intent != null) {
4407 if (intent.hasFileDescriptors()) {
4408 throw new IllegalArgumentException("File descriptors passed in Intent");
4409 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004410 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004411 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4412 throw new IllegalArgumentException(
4413 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4414 }
4415 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004416 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004417 }
4418 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004419 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004420 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004421 }
4422 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004423 if (options != null) {
4424 if (options.hasFileDescriptors()) {
4425 throw new IllegalArgumentException("File descriptors passed in options");
4426 }
4427 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004429 synchronized(this) {
4430 int callingUid = Binder.getCallingUid();
Dianne Hackborn41203752012-08-31 14:05:51 -07004431 userId = handleIncomingUserLocked(Binder.getCallingPid(), callingUid, userId,
4432 false, true, "getIntentSender", null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004433 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004434 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004435 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004436 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4437 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004438 String msg = "Permission Denial: getIntentSender() from pid="
4439 + Binder.getCallingPid()
4440 + ", uid=" + Binder.getCallingUid()
4441 + ", (need uid=" + uid + ")"
4442 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004443 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004444 throw new SecurityException(msg);
4445 }
4446 }
Dianne Hackborn41203752012-08-31 14:05:51 -07004447
4448 return getIntentSenderLocked(type, packageName, callingUid, userId,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004449 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004451 } catch (RemoteException e) {
4452 throw new SecurityException(e);
4453 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004454 }
4455 }
4456
Dianne Hackborn41203752012-08-31 14:05:51 -07004457 IIntentSender getIntentSenderLocked(int type, String packageName,
4458 int callingUid, int userId, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004459 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4460 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004461 if (DEBUG_MU)
4462 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004463 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004464 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004465 activity = mMainStack.isInStackLocked(token);
4466 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004467 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004469 if (activity.finishing) {
4470 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004471 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004472 }
4473
4474 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4475 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4476 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4477 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4478 |PendingIntent.FLAG_UPDATE_CURRENT);
4479
4480 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4481 type, packageName, activity, resultWho,
Dianne Hackborn41203752012-08-31 14:05:51 -07004482 requestCode, intents, resolvedTypes, flags, options, userId);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004483 WeakReference<PendingIntentRecord> ref;
4484 ref = mIntentSenderRecords.get(key);
4485 PendingIntentRecord rec = ref != null ? ref.get() : null;
4486 if (rec != null) {
4487 if (!cancelCurrent) {
4488 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004489 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004490 rec.key.requestIntent.replaceExtras(intents != null ?
4491 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004492 }
4493 if (intents != null) {
4494 intents[intents.length-1] = rec.key.requestIntent;
4495 rec.key.allIntents = intents;
4496 rec.key.allResolvedTypes = resolvedTypes;
4497 } else {
4498 rec.key.allIntents = null;
4499 rec.key.allResolvedTypes = null;
4500 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 return rec;
4503 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004504 rec.canceled = true;
4505 mIntentSenderRecords.remove(key);
4506 }
4507 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004508 return rec;
4509 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004510 rec = new PendingIntentRecord(this, key, callingUid);
4511 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004512 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004513 if (activity.pendingResults == null) {
4514 activity.pendingResults
4515 = new HashSet<WeakReference<PendingIntentRecord>>();
4516 }
4517 activity.pendingResults.add(rec.ref);
4518 }
4519 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004520 }
4521
4522 public void cancelIntentSender(IIntentSender sender) {
4523 if (!(sender instanceof PendingIntentRecord)) {
4524 return;
4525 }
4526 synchronized(this) {
4527 PendingIntentRecord rec = (PendingIntentRecord)sender;
4528 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004529 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004530 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4531 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 String msg = "Permission Denial: cancelIntentSender() from pid="
4533 + Binder.getCallingPid()
4534 + ", uid=" + Binder.getCallingUid()
4535 + " is not allowed to cancel packges "
4536 + rec.key.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 } catch (RemoteException e) {
4541 throw new SecurityException(e);
4542 }
4543 cancelIntentSenderLocked(rec, true);
4544 }
4545 }
4546
4547 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4548 rec.canceled = true;
4549 mIntentSenderRecords.remove(rec.key);
4550 if (cleanActivity && rec.key.activity != null) {
4551 rec.key.activity.pendingResults.remove(rec.ref);
4552 }
4553 }
4554
4555 public String getPackageForIntentSender(IIntentSender pendingResult) {
4556 if (!(pendingResult instanceof PendingIntentRecord)) {
4557 return null;
4558 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004559 try {
4560 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4561 return res.key.packageName;
4562 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004563 }
4564 return null;
4565 }
4566
Christopher Tatec4a07d12012-04-06 14:19:13 -07004567 public int getUidForIntentSender(IIntentSender sender) {
4568 if (sender instanceof PendingIntentRecord) {
4569 try {
4570 PendingIntentRecord res = (PendingIntentRecord)sender;
4571 return res.uid;
4572 } catch (ClassCastException e) {
4573 }
4574 }
4575 return -1;
4576 }
4577
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004578 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4579 if (!(pendingResult instanceof PendingIntentRecord)) {
4580 return false;
4581 }
4582 try {
4583 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4584 if (res.key.allIntents == null) {
4585 return false;
4586 }
4587 for (int i=0; i<res.key.allIntents.length; i++) {
4588 Intent intent = res.key.allIntents[i];
4589 if (intent.getPackage() != null && intent.getComponent() != null) {
4590 return false;
4591 }
4592 }
4593 return true;
4594 } catch (ClassCastException e) {
4595 }
4596 return false;
4597 }
4598
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004599 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4600 if (!(pendingResult instanceof PendingIntentRecord)) {
4601 return false;
4602 }
4603 try {
4604 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4605 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4606 return true;
4607 }
4608 return false;
4609 } catch (ClassCastException e) {
4610 }
4611 return false;
4612 }
4613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004614 public void setProcessLimit(int max) {
4615 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4616 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004617 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004618 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004619 mProcessLimitOverride = max;
4620 }
4621 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004622 }
4623
4624 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004625 synchronized (this) {
4626 return mProcessLimitOverride;
4627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004628 }
4629
4630 void foregroundTokenDied(ForegroundToken token) {
4631 synchronized (ActivityManagerService.this) {
4632 synchronized (mPidsSelfLocked) {
4633 ForegroundToken cur
4634 = mForegroundProcesses.get(token.pid);
4635 if (cur != token) {
4636 return;
4637 }
4638 mForegroundProcesses.remove(token.pid);
4639 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4640 if (pr == null) {
4641 return;
4642 }
4643 pr.forcingToForeground = null;
4644 pr.foregroundServices = false;
4645 }
4646 updateOomAdjLocked();
4647 }
4648 }
4649
4650 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4651 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4652 "setProcessForeground()");
4653 synchronized(this) {
4654 boolean changed = false;
4655
4656 synchronized (mPidsSelfLocked) {
4657 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004658 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004659 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004660 return;
4661 }
4662 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4663 if (oldToken != null) {
4664 oldToken.token.unlinkToDeath(oldToken, 0);
4665 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004666 if (pr != null) {
4667 pr.forcingToForeground = null;
4668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004669 changed = true;
4670 }
4671 if (isForeground && token != null) {
4672 ForegroundToken newToken = new ForegroundToken() {
4673 public void binderDied() {
4674 foregroundTokenDied(this);
4675 }
4676 };
4677 newToken.pid = pid;
4678 newToken.token = token;
4679 try {
4680 token.linkToDeath(newToken, 0);
4681 mForegroundProcesses.put(pid, newToken);
4682 pr.forcingToForeground = token;
4683 changed = true;
4684 } catch (RemoteException e) {
4685 // If the process died while doing this, we will later
4686 // do the cleanup with the process death link.
4687 }
4688 }
4689 }
4690
4691 if (changed) {
4692 updateOomAdjLocked();
4693 }
4694 }
4695 }
4696
4697 // =========================================================
4698 // PERMISSIONS
4699 // =========================================================
4700
4701 static class PermissionController extends IPermissionController.Stub {
4702 ActivityManagerService mActivityManagerService;
4703 PermissionController(ActivityManagerService activityManagerService) {
4704 mActivityManagerService = activityManagerService;
4705 }
4706
4707 public boolean checkPermission(String permission, int pid, int uid) {
4708 return mActivityManagerService.checkPermission(permission, pid,
4709 uid) == PackageManager.PERMISSION_GRANTED;
4710 }
4711 }
4712
4713 /**
4714 * This can be called with or without the global lock held.
4715 */
4716 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004717 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004718 // We might be performing an operation on behalf of an indirect binder
4719 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4720 // client identity accordingly before proceeding.
4721 Identity tlsIdentity = sCallerIdentity.get();
4722 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004723 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004724 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4725 uid = tlsIdentity.uid;
4726 pid = tlsIdentity.pid;
4727 }
4728
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004729 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004730 return PackageManager.PERMISSION_GRANTED;
4731 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004732
4733 return ActivityManager.checkComponentPermission(permission, uid,
4734 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 }
4736
4737 /**
4738 * As the only public entry point for permissions checking, this method
4739 * can enforce the semantic that requesting a check on a null global
4740 * permission is automatically denied. (Internally a null permission
4741 * string is used when calling {@link #checkComponentPermission} in cases
4742 * when only uid-based security is needed.)
4743 *
4744 * This can be called with or without the global lock held.
4745 */
4746 public int checkPermission(String permission, int pid, int uid) {
4747 if (permission == null) {
4748 return PackageManager.PERMISSION_DENIED;
4749 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004750 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004751 }
4752
4753 /**
4754 * Binder IPC calls go through the public entry point.
4755 * This can be called with or without the global lock held.
4756 */
4757 int checkCallingPermission(String permission) {
4758 return checkPermission(permission,
4759 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004760 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004761 }
4762
4763 /**
4764 * This can be called with or without the global lock held.
4765 */
4766 void enforceCallingPermission(String permission, String func) {
4767 if (checkCallingPermission(permission)
4768 == PackageManager.PERMISSION_GRANTED) {
4769 return;
4770 }
4771
4772 String msg = "Permission Denial: " + func + " from pid="
4773 + Binder.getCallingPid()
4774 + ", uid=" + Binder.getCallingUid()
4775 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004776 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004777 throw new SecurityException(msg);
4778 }
4779
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004780 /**
4781 * Determine if UID is holding permissions required to access {@link Uri} in
4782 * the given {@link ProviderInfo}. Final permission checking is always done
4783 * in {@link ContentProvider}.
4784 */
4785 private final boolean checkHoldingPermissionsLocked(
4786 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004787 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4788 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004789
4790 if (pi.applicationInfo.uid == uid) {
4791 return true;
4792 } else if (!pi.exported) {
4793 return false;
4794 }
4795
4796 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4797 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004798 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004799 // check if target holds top-level <provider> permissions
4800 if (!readMet && pi.readPermission != null
4801 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4802 readMet = true;
4803 }
4804 if (!writeMet && pi.writePermission != null
4805 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4806 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004807 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004808
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004809 // track if unprotected read/write is allowed; any denied
4810 // <path-permission> below removes this ability
4811 boolean allowDefaultRead = pi.readPermission == null;
4812 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004813
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004814 // check if target holds any <path-permission> that match uri
4815 final PathPermission[] pps = pi.pathPermissions;
4816 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004817 final String path = uri.getPath();
4818 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004819 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004820 i--;
4821 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004822 if (pp.match(path)) {
4823 if (!readMet) {
4824 final String pprperm = pp.getReadPermission();
4825 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4826 + pprperm + " for " + pp.getPath()
4827 + ": match=" + pp.match(path)
4828 + " check=" + pm.checkUidPermission(pprperm, uid));
4829 if (pprperm != null) {
4830 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4831 readMet = true;
4832 } else {
4833 allowDefaultRead = false;
4834 }
4835 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004836 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004837 if (!writeMet) {
4838 final String ppwperm = pp.getWritePermission();
4839 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4840 + ppwperm + " for " + pp.getPath()
4841 + ": match=" + pp.match(path)
4842 + " check=" + pm.checkUidPermission(ppwperm, uid));
4843 if (ppwperm != null) {
4844 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4845 writeMet = true;
4846 } else {
4847 allowDefaultWrite = false;
4848 }
4849 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004850 }
4851 }
4852 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004853 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004854
4855 // grant unprotected <provider> read/write, if not blocked by
4856 // <path-permission> above
4857 if (allowDefaultRead) readMet = true;
4858 if (allowDefaultWrite) writeMet = true;
4859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004860 } catch (RemoteException e) {
4861 return false;
4862 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004863
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004864 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004865 }
4866
4867 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4868 int modeFlags) {
4869 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004870 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004871 return true;
4872 }
4873 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4874 if (perms == null) return false;
4875 UriPermission perm = perms.get(uri);
4876 if (perm == null) return false;
4877 return (modeFlags&perm.modeFlags) == modeFlags;
4878 }
4879
4880 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004881 enforceNotIsolatedCaller("checkUriPermission");
4882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004883 // Another redirected-binder-call permissions check as in
4884 // {@link checkComponentPermission}.
4885 Identity tlsIdentity = sCallerIdentity.get();
4886 if (tlsIdentity != null) {
4887 uid = tlsIdentity.uid;
4888 pid = tlsIdentity.pid;
4889 }
4890
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004891 uid = UserHandle.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004892 // Our own process gets to do everything.
4893 if (pid == MY_PID) {
4894 return PackageManager.PERMISSION_GRANTED;
4895 }
4896 synchronized(this) {
4897 return checkUriPermissionLocked(uri, uid, modeFlags)
4898 ? PackageManager.PERMISSION_GRANTED
4899 : PackageManager.PERMISSION_DENIED;
4900 }
4901 }
4902
Dianne Hackborn39792d22010-08-19 18:01:52 -07004903 /**
4904 * Check if the targetPkg can be granted permission to access uri by
4905 * the callingUid using the given modeFlags. Throws a security exception
4906 * if callingUid is not allowed to do this. Returns the uid of the target
4907 * if the URI permission grant should be performed; returns -1 if it is not
4908 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004909 * If you already know the uid of the target, you can supply it in
4910 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004911 */
4912 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004913 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004914 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4915 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4916 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004917 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004918 }
4919
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004920 if (targetPkg != null) {
4921 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4922 "Checking grant " + targetPkg + " permission to " + uri);
4923 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004924
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004925 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004926
4927 // If this is not a content: uri, we can't do anything with it.
4928 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004929 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004930 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004931 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004932 }
4933
4934 String name = uri.getAuthority();
4935 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004936 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004937 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004938 if (cpr != null) {
4939 pi = cpr.info;
4940 } else {
4941 try {
4942 pi = pm.resolveContentProvider(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004943 PackageManager.GET_URI_PERMISSION_PATTERNS, UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004944 } catch (RemoteException ex) {
4945 }
4946 }
4947 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004948 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004949 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004950 }
4951
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004952 int targetUid = lastTargetUid;
4953 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004954 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004955 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004956 if (targetUid < 0) {
4957 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4958 "Can't grant URI permission no uid for: " + targetPkg);
4959 return -1;
4960 }
4961 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004962 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004964 }
4965
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004966 if (targetUid >= 0) {
4967 // First... does the target actually need this permission?
4968 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4969 // No need to grant the target this permission.
4970 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4971 "Target " + targetPkg + " already has full permission to " + uri);
4972 return -1;
4973 }
4974 } else {
4975 // First... there is no target package, so can anyone access it?
4976 boolean allowed = pi.exported;
4977 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4978 if (pi.readPermission != null) {
4979 allowed = false;
4980 }
4981 }
4982 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4983 if (pi.writePermission != null) {
4984 allowed = false;
4985 }
4986 }
4987 if (allowed) {
4988 return -1;
4989 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004990 }
4991
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004992 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004993 if (!pi.grantUriPermissions) {
4994 throw new SecurityException("Provider " + pi.packageName
4995 + "/" + pi.name
4996 + " does not allow granting of Uri permissions (uri "
4997 + uri + ")");
4998 }
4999 if (pi.uriPermissionPatterns != null) {
5000 final int N = pi.uriPermissionPatterns.length;
5001 boolean allowed = false;
5002 for (int i=0; i<N; i++) {
5003 if (pi.uriPermissionPatterns[i] != null
5004 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5005 allowed = true;
5006 break;
5007 }
5008 }
5009 if (!allowed) {
5010 throw new SecurityException("Provider " + pi.packageName
5011 + "/" + pi.name
5012 + " does not allow granting of permission to path of Uri "
5013 + uri);
5014 }
5015 }
5016
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005017 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005018 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005019 if (callingUid != Process.myUid()) {
5020 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5021 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5022 throw new SecurityException("Uid " + callingUid
5023 + " does not have permission to uri " + uri);
5024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005025 }
5026 }
5027
Dianne Hackborn39792d22010-08-19 18:01:52 -07005028 return targetUid;
5029 }
5030
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005031 public int checkGrantUriPermission(int callingUid, String targetPkg,
5032 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005033 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005034 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005035 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005036 }
5037 }
5038
Dianne Hackborn39792d22010-08-19 18:01:52 -07005039 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5040 Uri uri, int modeFlags, UriPermissionOwner owner) {
5041 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5042 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5043 if (modeFlags == 0) {
5044 return;
5045 }
5046
5047 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005048 // to the uri, and the target doesn't. Let's now give this to
5049 // the target.
5050
Joe Onorato8a9b2202010-02-26 18:56:32 -08005051 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005052 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005053
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005054 HashMap<Uri, UriPermission> targetUris
5055 = mGrantedUriPermissions.get(targetUid);
5056 if (targetUris == null) {
5057 targetUris = new HashMap<Uri, UriPermission>();
5058 mGrantedUriPermissions.put(targetUid, targetUris);
5059 }
5060
5061 UriPermission perm = targetUris.get(uri);
5062 if (perm == null) {
5063 perm = new UriPermission(targetUid, uri);
5064 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005065 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005067 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005068 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005069 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005070 } else {
5071 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5072 perm.readOwners.add(owner);
5073 owner.addReadPermission(perm);
5074 }
5075 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5076 perm.writeOwners.add(owner);
5077 owner.addWritePermission(perm);
5078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005079 }
5080 }
5081
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005082 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5083 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005084 if (targetPkg == null) {
5085 throw new NullPointerException("targetPkg");
5086 }
5087
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005088 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005089 if (targetUid < 0) {
5090 return;
5091 }
5092
5093 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5094 }
5095
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005096 static class NeededUriGrants extends ArrayList<Uri> {
5097 final String targetPkg;
5098 final int targetUid;
5099 final int flags;
5100
5101 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5102 targetPkg = _targetPkg;
5103 targetUid = _targetUid;
5104 flags = _flags;
5105 }
5106 }
5107
Dianne Hackborn39792d22010-08-19 18:01:52 -07005108 /**
5109 * Like checkGrantUriPermissionLocked, but takes an Intent.
5110 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005111 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5112 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005113 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005114 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5115 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005116 + " from " + intent + "; flags=0x"
5117 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5118
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005119 if (targetPkg == null) {
5120 throw new NullPointerException("targetPkg");
5121 }
5122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005123 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005124 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005125 }
5126 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005127 ClipData clip = intent.getClipData();
5128 if (data == null && clip == null) {
5129 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005130 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005131 if (data != null) {
5132 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5133 mode, needed != null ? needed.targetUid : -1);
5134 if (target > 0) {
5135 if (needed == null) {
5136 needed = new NeededUriGrants(targetPkg, target, mode);
5137 }
5138 needed.add(data);
5139 }
5140 }
5141 if (clip != null) {
5142 for (int i=0; i<clip.getItemCount(); i++) {
5143 Uri uri = clip.getItemAt(i).getUri();
5144 if (uri != null) {
5145 int target = -1;
5146 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5147 mode, needed != null ? needed.targetUid : -1);
5148 if (target > 0) {
5149 if (needed == null) {
5150 needed = new NeededUriGrants(targetPkg, target, mode);
5151 }
5152 needed.add(uri);
5153 }
5154 } else {
5155 Intent clipIntent = clip.getItemAt(i).getIntent();
5156 if (clipIntent != null) {
5157 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5158 callingUid, targetPkg, clipIntent, mode, needed);
5159 if (newNeeded != null) {
5160 needed = newNeeded;
5161 }
5162 }
5163 }
5164 }
5165 }
5166
5167 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005168 }
5169
5170 /**
5171 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5172 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005173 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5174 UriPermissionOwner owner) {
5175 if (needed != null) {
5176 for (int i=0; i<needed.size(); i++) {
5177 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5178 needed.get(i), needed.flags, owner);
5179 }
5180 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005181 }
5182
5183 void grantUriPermissionFromIntentLocked(int callingUid,
5184 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005185 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005186 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005187 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005188 return;
5189 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005190
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005191 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005192 }
5193
5194 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5195 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005196 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005197 synchronized(this) {
5198 final ProcessRecord r = getRecordForAppLocked(caller);
5199 if (r == null) {
5200 throw new SecurityException("Unable to find app for caller "
5201 + caller
5202 + " when granting permission to uri " + uri);
5203 }
5204 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005205 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005206 }
5207 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005208 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005209 }
5210
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005211 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005212 null);
5213 }
5214 }
5215
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005216 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005217 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5218 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5219 HashMap<Uri, UriPermission> perms
5220 = mGrantedUriPermissions.get(perm.uid);
5221 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005222 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005223 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005224 perms.remove(perm.uri);
5225 if (perms.size() == 0) {
5226 mGrantedUriPermissions.remove(perm.uid);
5227 }
5228 }
5229 }
5230 }
5231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005232 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5233 int modeFlags) {
5234 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5235 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5236 if (modeFlags == 0) {
5237 return;
5238 }
5239
Joe Onorato8a9b2202010-02-26 18:56:32 -08005240 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005241 "Revoking all granted permissions to " + uri);
5242
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005243 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005244
5245 final String authority = uri.getAuthority();
5246 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005247 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005248 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005249 if (cpr != null) {
5250 pi = cpr.info;
5251 } else {
5252 try {
5253 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005254 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005255 } catch (RemoteException ex) {
5256 }
5257 }
5258 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005259 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005260 return;
5261 }
5262
5263 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005264 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005265 // Right now, if you are not the original owner of the permission,
5266 // you are not allowed to revoke it.
5267 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5268 throw new SecurityException("Uid " + callingUid
5269 + " does not have permission to uri " + uri);
5270 //}
5271 }
5272
5273 // Go through all of the permissions and remove any that match.
5274 final List<String> SEGMENTS = uri.getPathSegments();
5275 if (SEGMENTS != null) {
5276 final int NS = SEGMENTS.size();
5277 int N = mGrantedUriPermissions.size();
5278 for (int i=0; i<N; i++) {
5279 HashMap<Uri, UriPermission> perms
5280 = mGrantedUriPermissions.valueAt(i);
5281 Iterator<UriPermission> it = perms.values().iterator();
5282 toploop:
5283 while (it.hasNext()) {
5284 UriPermission perm = it.next();
5285 Uri targetUri = perm.uri;
5286 if (!authority.equals(targetUri.getAuthority())) {
5287 continue;
5288 }
5289 List<String> targetSegments = targetUri.getPathSegments();
5290 if (targetSegments == null) {
5291 continue;
5292 }
5293 if (targetSegments.size() < NS) {
5294 continue;
5295 }
5296 for (int j=0; j<NS; j++) {
5297 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5298 continue toploop;
5299 }
5300 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005301 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005302 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005303 perm.clearModes(modeFlags);
5304 if (perm.modeFlags == 0) {
5305 it.remove();
5306 }
5307 }
5308 if (perms.size() == 0) {
5309 mGrantedUriPermissions.remove(
5310 mGrantedUriPermissions.keyAt(i));
5311 N--;
5312 i--;
5313 }
5314 }
5315 }
5316 }
5317
5318 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5319 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005320 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005321 synchronized(this) {
5322 final ProcessRecord r = getRecordForAppLocked(caller);
5323 if (r == null) {
5324 throw new SecurityException("Unable to find app for caller "
5325 + caller
5326 + " when revoking permission to uri " + uri);
5327 }
5328 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005329 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005330 return;
5331 }
5332
5333 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5334 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5335 if (modeFlags == 0) {
5336 return;
5337 }
5338
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005339 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005340
5341 final String authority = uri.getAuthority();
5342 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005343 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005344 if (cpr != null) {
5345 pi = cpr.info;
5346 } else {
5347 try {
5348 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005349 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005350 } catch (RemoteException ex) {
5351 }
5352 }
5353 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005354 Slog.w(TAG, "No content provider found for permission revoke: "
5355 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005356 return;
5357 }
5358
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005359 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005360 }
5361 }
5362
Dianne Hackborn7e269642010-08-25 19:50:20 -07005363 @Override
5364 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005365 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005366 synchronized(this) {
5367 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5368 return owner.getExternalTokenLocked();
5369 }
5370 }
5371
5372 @Override
5373 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5374 Uri uri, int modeFlags) {
5375 synchronized(this) {
5376 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5377 if (owner == null) {
5378 throw new IllegalArgumentException("Unknown owner: " + token);
5379 }
5380 if (fromUid != Binder.getCallingUid()) {
5381 if (Binder.getCallingUid() != Process.myUid()) {
5382 // Only system code can grant URI permissions on behalf
5383 // of other users.
5384 throw new SecurityException("nice try");
5385 }
5386 }
5387 if (targetPkg == null) {
5388 throw new IllegalArgumentException("null target");
5389 }
5390 if (uri == null) {
5391 throw new IllegalArgumentException("null uri");
5392 }
5393
5394 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5395 }
5396 }
5397
5398 @Override
5399 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5400 synchronized(this) {
5401 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5402 if (owner == null) {
5403 throw new IllegalArgumentException("Unknown owner: " + token);
5404 }
5405
5406 if (uri == null) {
5407 owner.removeUriPermissionsLocked(mode);
5408 } else {
5409 owner.removeUriPermissionLocked(uri, mode);
5410 }
5411 }
5412 }
5413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005414 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5415 synchronized (this) {
5416 ProcessRecord app =
5417 who != null ? getRecordForAppLocked(who) : null;
5418 if (app == null) return;
5419
5420 Message msg = Message.obtain();
5421 msg.what = WAIT_FOR_DEBUGGER_MSG;
5422 msg.obj = app;
5423 msg.arg1 = waiting ? 1 : 0;
5424 mHandler.sendMessage(msg);
5425 }
5426 }
5427
5428 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005429 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5430 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005431 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005432 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005433 outInfo.threshold = homeAppMem;
5434 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5435 outInfo.hiddenAppThreshold = hiddenAppMem;
5436 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005437 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005438 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5439 ProcessList.VISIBLE_APP_ADJ);
5440 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5441 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005442 }
5443
5444 // =========================================================
5445 // TASK MANAGEMENT
5446 // =========================================================
5447
5448 public List getTasks(int maxNum, int flags,
5449 IThumbnailReceiver receiver) {
5450 ArrayList list = new ArrayList();
5451
5452 PendingThumbnailsRecord pending = null;
5453 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005454 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455
5456 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005457 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005458 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5459 + ", receiver=" + receiver);
5460
5461 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5462 != PackageManager.PERMISSION_GRANTED) {
5463 if (receiver != null) {
5464 // If the caller wants to wait for pending thumbnails,
5465 // it ain't gonna get them.
5466 try {
5467 receiver.finished();
5468 } catch (RemoteException ex) {
5469 }
5470 }
5471 String msg = "Permission Denial: getTasks() from pid="
5472 + Binder.getCallingPid()
5473 + ", uid=" + Binder.getCallingUid()
5474 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005475 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005476 throw new SecurityException(msg);
5477 }
5478
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005479 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005480 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005481 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005482 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 TaskRecord curTask = null;
5484 int numActivities = 0;
5485 int numRunning = 0;
5486 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005487 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005489 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005490
5491 // Initialize state for next task if needed.
5492 if (top == null ||
5493 (top.state == ActivityState.INITIALIZING
5494 && top.task == r.task)) {
5495 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496 curTask = r.task;
5497 numActivities = numRunning = 0;
5498 }
5499
5500 // Add 'r' into the current task.
5501 numActivities++;
5502 if (r.app != null && r.app.thread != null) {
5503 numRunning++;
5504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005505
Joe Onorato8a9b2202010-02-26 18:56:32 -08005506 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 TAG, r.intent.getComponent().flattenToShortString()
5508 + ": task=" + r.task);
5509
5510 // If the next one is a different task, generate a new
5511 // TaskInfo entry for what we have.
5512 if (next == null || next.task != curTask) {
5513 ActivityManager.RunningTaskInfo ci
5514 = new ActivityManager.RunningTaskInfo();
5515 ci.id = curTask.taskId;
5516 ci.baseActivity = r.intent.getComponent();
5517 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005518 if (top.thumbHolder != null) {
5519 ci.description = top.thumbHolder.lastDescription;
5520 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005521 ci.numActivities = numActivities;
5522 ci.numRunning = numRunning;
5523 //System.out.println(
5524 // "#" + maxNum + ": " + " descr=" + ci.description);
5525 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005526 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005527 TAG, "State=" + top.state + "Idle=" + top.idle
5528 + " app=" + top.app
5529 + " thr=" + (top.app != null ? top.app.thread : null));
5530 if (top.state == ActivityState.RESUMED
5531 || top.state == ActivityState.PAUSING) {
5532 if (top.idle && top.app != null
5533 && top.app.thread != null) {
5534 topRecord = top;
5535 topThumbnail = top.app.thread;
5536 } else {
5537 top.thumbnailNeeded = true;
5538 }
5539 }
5540 if (pending == null) {
5541 pending = new PendingThumbnailsRecord(receiver);
5542 }
5543 pending.pendingRecords.add(top);
5544 }
5545 list.add(ci);
5546 maxNum--;
5547 top = null;
5548 }
5549 }
5550
5551 if (pending != null) {
5552 mPendingThumbnails.add(pending);
5553 }
5554 }
5555
Joe Onorato8a9b2202010-02-26 18:56:32 -08005556 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557
5558 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005559 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005560 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005561 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005562 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005563 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005564 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 }
5566 }
5567
5568 if (pending == null && receiver != null) {
5569 // In this case all thumbnails were available and the client
5570 // is being asked to be told when the remaining ones come in...
5571 // which is unusually, since the top-most currently running
5572 // activity should never have a canned thumbnail! Oh well.
5573 try {
5574 receiver.finished();
5575 } catch (RemoteException ex) {
5576 }
5577 }
5578
5579 return list;
5580 }
5581
5582 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005583 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005584 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005585 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07005586 // Check if the caller is holding permissions for cross-user requests.
5587 if (checkComponentPermission(
5588 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5589 Binder.getCallingPid(), callingUid, -1, true)
5590 != PackageManager.PERMISSION_GRANTED) {
5591 String msg = "Permission Denial: "
5592 + "Request to get recent tasks for user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005593 + " but is calling from user " + UserHandle.getUserId(callingUid)
Amith Yamasani82644082012-08-03 13:09:11 -07005594 + "; this requires "
5595 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5596 Slog.w(TAG, msg);
5597 throw new SecurityException(msg);
5598 } else {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005599 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07005600 userId = mCurrentUserId;
5601 }
5602 }
5603 }
5604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005605 synchronized (this) {
5606 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5607 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005608 final boolean detailed = checkCallingPermission(
5609 android.Manifest.permission.GET_DETAILED_TASKS)
5610 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005612 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 final int N = mRecentTasks.size();
5615 ArrayList<ActivityManager.RecentTaskInfo> res
5616 = new ArrayList<ActivityManager.RecentTaskInfo>(
5617 maxNum < N ? maxNum : N);
5618 for (int i=0; i<N && maxNum > 0; i++) {
5619 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005620 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005621 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005622 // Return the entry if desired by the caller. We always return
5623 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005624 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005625 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5626 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005627
Dianne Hackborn905577f2011-09-07 18:31:28 -07005628 if (i == 0
5629 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 || (tr.intent == null)
5631 || ((tr.intent.getFlags()
5632 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5633 ActivityManager.RecentTaskInfo rti
5634 = new ActivityManager.RecentTaskInfo();
5635 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005636 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 rti.baseIntent = new Intent(
5638 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005639 if (!detailed) {
5640 rti.baseIntent.replaceExtras((Bundle)null);
5641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005643 rti.description = tr.lastDescription;
5644
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005645 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5646 // Check whether this activity is currently available.
5647 try {
5648 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005649 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005650 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005651 continue;
5652 }
5653 } else if (rti.baseIntent != null) {
5654 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005655 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005656 continue;
5657 }
5658 }
5659 } catch (RemoteException e) {
5660 // Will never happen.
5661 }
5662 }
5663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005664 res.add(rti);
5665 maxNum--;
5666 }
5667 }
5668 return res;
5669 }
5670 }
5671
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005672 private TaskRecord taskForIdLocked(int id) {
5673 final int N = mRecentTasks.size();
5674 for (int i=0; i<N; i++) {
5675 TaskRecord tr = mRecentTasks.get(i);
5676 if (tr.taskId == id) {
5677 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005678 }
5679 }
5680 return null;
5681 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005682
5683 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5684 synchronized (this) {
5685 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5686 "getTaskThumbnails()");
5687 TaskRecord tr = taskForIdLocked(id);
5688 if (tr != null) {
5689 return mMainStack.getTaskThumbnailsLocked(tr);
5690 }
5691 }
5692 return null;
5693 }
5694
5695 public boolean removeSubTask(int taskId, int subTaskIndex) {
5696 synchronized (this) {
5697 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5698 "removeSubTask()");
5699 long ident = Binder.clearCallingIdentity();
5700 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005701 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5702 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005703 } finally {
5704 Binder.restoreCallingIdentity(ident);
5705 }
5706 }
5707 }
5708
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005709 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5710 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005711 Intent baseIntent = new Intent(
5712 tr.intent != null ? tr.intent : tr.affinityIntent);
5713 ComponentName component = baseIntent.getComponent();
5714 if (component == null) {
5715 Slog.w(TAG, "Now component for base intent of task: " + tr);
5716 return;
5717 }
5718
5719 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005720 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005721
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005722 if (killProcesses) {
5723 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005724 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005725 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005726 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5727 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5728 for (int i=0; i<uids.size(); i++) {
5729 ProcessRecord proc = uids.valueAt(i);
5730 if (proc.userId != tr.userId) {
5731 continue;
5732 }
5733 if (!proc.pkgList.contains(pkg)) {
5734 continue;
5735 }
5736 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005737 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005738 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005739
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005740 // Kill the running processes.
5741 for (int i=0; i<procs.size(); i++) {
5742 ProcessRecord pr = procs.get(i);
5743 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5744 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5745 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5746 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005747 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005748 Process.killProcessQuiet(pr.pid);
5749 } else {
5750 pr.waitingToKill = "remove task";
5751 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005752 }
5753 }
5754 }
5755
5756 public boolean removeTask(int taskId, int flags) {
5757 synchronized (this) {
5758 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5759 "removeTask()");
5760 long ident = Binder.clearCallingIdentity();
5761 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005762 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5763 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005764 if (r != null) {
5765 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005766 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005767 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005768 } else {
5769 TaskRecord tr = null;
5770 int i=0;
5771 while (i < mRecentTasks.size()) {
5772 TaskRecord t = mRecentTasks.get(i);
5773 if (t.taskId == taskId) {
5774 tr = t;
5775 break;
5776 }
5777 i++;
5778 }
5779 if (tr != null) {
5780 if (tr.numActivities <= 0) {
5781 // Caller is just removing a recent task that is
5782 // not actively running. That is easy!
5783 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005784 cleanUpRemovedTaskLocked(tr, flags);
5785 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005786 } else {
5787 Slog.w(TAG, "removeTask: task " + taskId
5788 + " does not have activities to remove, "
5789 + " but numActivities=" + tr.numActivities
5790 + ": " + tr);
5791 }
5792 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005793 }
5794 } finally {
5795 Binder.restoreCallingIdentity(ident);
5796 }
5797 }
5798 return false;
5799 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005801 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5802 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005803 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005804 TaskRecord jt = startTask;
5805
5806 // First look backwards
5807 for (j=startIndex-1; j>=0; j--) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005808 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005809 if (r.task != jt) {
5810 jt = r.task;
5811 if (affinity.equals(jt.affinity)) {
5812 return j;
5813 }
5814 }
5815 }
5816
5817 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005818 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005819 jt = startTask;
5820 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005821 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 if (r.task != jt) {
5823 if (affinity.equals(jt.affinity)) {
5824 return j;
5825 }
5826 jt = r.task;
5827 }
5828 }
5829
5830 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005831 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 return N-1;
5833 }
5834
5835 return -1;
5836 }
5837
5838 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005839 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005840 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005841 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005842 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5843 "moveTaskToFront()");
5844
5845 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005846 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5847 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005848 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005849 return;
5850 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851 final long origId = Binder.clearCallingIdentity();
5852 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005853 TaskRecord tr = taskForIdLocked(task);
5854 if (tr != null) {
5855 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5856 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005858 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5859 // Caller wants the home activity moved with it. To accomplish this,
5860 // we'll just move the home task to the top first.
5861 mMainStack.moveHomeToFrontLocked();
5862 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005863 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005864 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005865 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005866 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5867 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005869 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5870 mMainStack.mUserLeaving = true;
5871 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005872 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5873 // Caller wants the home activity moved with it. To accomplish this,
5874 // we'll just move the home task to the top first.
5875 mMainStack.moveHomeToFrontLocked();
5876 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005877 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005878 return;
5879 }
5880 }
5881 } finally {
5882 Binder.restoreCallingIdentity(origId);
5883 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005884 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005885 }
5886 }
5887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 public void moveTaskToBack(int task) {
5889 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5890 "moveTaskToBack()");
5891
5892 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005893 if (mMainStack.mResumedActivity != null
5894 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005895 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5896 Binder.getCallingUid(), "Task to back")) {
5897 return;
5898 }
5899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005901 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005902 Binder.restoreCallingIdentity(origId);
5903 }
5904 }
5905
5906 /**
5907 * Moves an activity, and all of the other activities within the same task, to the bottom
5908 * of the history stack. The activity's order within the task is unchanged.
5909 *
5910 * @param token A reference to the activity we wish to move
5911 * @param nonRoot If false then this only works if the activity is the root
5912 * of a task; if true it will work for any activity in a task.
5913 * @return Returns true if the move completed, false if not.
5914 */
5915 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005916 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005917 synchronized(this) {
5918 final long origId = Binder.clearCallingIdentity();
5919 int taskId = getTaskForActivityLocked(token, !nonRoot);
5920 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005921 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005922 }
5923 Binder.restoreCallingIdentity(origId);
5924 }
5925 return false;
5926 }
5927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005928 public void moveTaskBackwards(int task) {
5929 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5930 "moveTaskBackwards()");
5931
5932 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005933 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5934 Binder.getCallingUid(), "Task backwards")) {
5935 return;
5936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005937 final long origId = Binder.clearCallingIdentity();
5938 moveTaskBackwardsLocked(task);
5939 Binder.restoreCallingIdentity(origId);
5940 }
5941 }
5942
5943 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005944 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 }
5946
5947 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5948 synchronized(this) {
5949 return getTaskForActivityLocked(token, onlyRoot);
5950 }
5951 }
5952
5953 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005954 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005955 TaskRecord lastTask = null;
5956 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005957 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005958 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 if (!onlyRoot || lastTask != r.task) {
5960 return r.task.taskId;
5961 }
5962 return -1;
5963 }
5964 lastTask = r.task;
5965 }
5966
5967 return -1;
5968 }
5969
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 // =========================================================
5971 // THUMBNAILS
5972 // =========================================================
5973
5974 public void reportThumbnail(IBinder token,
5975 Bitmap thumbnail, CharSequence description) {
5976 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5977 final long origId = Binder.clearCallingIdentity();
5978 sendPendingThumbnail(null, token, thumbnail, description, true);
5979 Binder.restoreCallingIdentity(origId);
5980 }
5981
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005982 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 Bitmap thumbnail, CharSequence description, boolean always) {
5984 TaskRecord task = null;
5985 ArrayList receivers = null;
5986
5987 //System.out.println("Send pending thumbnail: " + r);
5988
5989 synchronized(this) {
5990 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07005991 r = mMainStack.isInStackLocked(token);
5992 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005993 return;
5994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005995 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005996 if (thumbnail == null && r.thumbHolder != null) {
5997 thumbnail = r.thumbHolder.lastThumbnail;
5998 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 }
6000 if (thumbnail == null && !always) {
6001 // If there is no thumbnail, and this entry is not actually
6002 // going away, then abort for now and pick up the next
6003 // thumbnail we get.
6004 return;
6005 }
6006 task = r.task;
6007
6008 int N = mPendingThumbnails.size();
6009 int i=0;
6010 while (i<N) {
6011 PendingThumbnailsRecord pr =
6012 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6013 //System.out.println("Looking in " + pr.pendingRecords);
6014 if (pr.pendingRecords.remove(r)) {
6015 if (receivers == null) {
6016 receivers = new ArrayList();
6017 }
6018 receivers.add(pr);
6019 if (pr.pendingRecords.size() == 0) {
6020 pr.finished = true;
6021 mPendingThumbnails.remove(i);
6022 N--;
6023 continue;
6024 }
6025 }
6026 i++;
6027 }
6028 }
6029
6030 if (receivers != null) {
6031 final int N = receivers.size();
6032 for (int i=0; i<N; i++) {
6033 try {
6034 PendingThumbnailsRecord pr =
6035 (PendingThumbnailsRecord)receivers.get(i);
6036 pr.receiver.newThumbnail(
6037 task != null ? task.taskId : -1, thumbnail, description);
6038 if (pr.finished) {
6039 pr.receiver.finished();
6040 }
6041 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006042 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 }
6044 }
6045 }
6046 }
6047
6048 // =========================================================
6049 // CONTENT PROVIDERS
6050 // =========================================================
6051
Jeff Brown10e89712011-07-08 18:52:57 -07006052 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6053 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006054 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006055 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006056 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006057 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006058 } catch (RemoteException ex) {
6059 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006060 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006061 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6062 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006063 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006064 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006065 for (int i=0; i<N; i++) {
6066 ProviderInfo cpi =
6067 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006068 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6069 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006070 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006071 // This is a singleton provider, but a user besides the
6072 // default user is asking to initialize a process it runs
6073 // in... well, no, it doesn't actually run in this process,
6074 // it runs in the process of the default user. Get rid of it.
6075 providers.remove(i);
6076 N--;
6077 continue;
6078 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006079
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006080 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006081 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006083 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006084 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006085 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006086 if (DEBUG_MU)
6087 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 app.pubProviders.put(cpi.name, cpr);
6089 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006090 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006091 }
6092 }
6093 return providers;
6094 }
6095
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006096 /**
6097 * Check if {@link ProcessRecord} has a possible chance at accessing the
6098 * given {@link ProviderInfo}. Final permission checking is always done
6099 * in {@link ContentProvider}.
6100 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006101 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006102 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006104 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006106 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006107 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006108 return null;
6109 }
6110 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006111 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006112 == PackageManager.PERMISSION_GRANTED) {
6113 return null;
6114 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006115
6116 PathPermission[] pps = cpi.pathPermissions;
6117 if (pps != null) {
6118 int i = pps.length;
6119 while (i > 0) {
6120 i--;
6121 PathPermission pp = pps[i];
6122 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006123 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006124 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006125 return null;
6126 }
6127 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006128 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006129 == PackageManager.PERMISSION_GRANTED) {
6130 return null;
6131 }
6132 }
6133 }
6134
Dianne Hackbornb424b632010-08-18 15:59:05 -07006135 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6136 if (perms != null) {
6137 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6138 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6139 return null;
6140 }
6141 }
6142 }
6143
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006144 String msg;
6145 if (!cpi.exported) {
6146 msg = "Permission Denial: opening provider " + cpi.name
6147 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6148 + ", uid=" + callingUid + ") that is not exported from uid "
6149 + cpi.applicationInfo.uid;
6150 } else {
6151 msg = "Permission Denial: opening provider " + cpi.name
6152 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6153 + ", uid=" + callingUid + ") requires "
6154 + cpi.readPermission + " or " + cpi.writePermission;
6155 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006156 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 return msg;
6158 }
6159
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006160 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6161 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006162 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006163 for (int i=0; i<r.conProviders.size(); i++) {
6164 ContentProviderConnection conn = r.conProviders.get(i);
6165 if (conn.provider == cpr) {
6166 if (DEBUG_PROVIDER) Slog.v(TAG,
6167 "Adding provider requested by "
6168 + r.processName + " from process "
6169 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6170 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6171 if (stable) {
6172 conn.stableCount++;
6173 conn.numStableIncs++;
6174 } else {
6175 conn.unstableCount++;
6176 conn.numUnstableIncs++;
6177 }
6178 return conn;
6179 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006180 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006181 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6182 if (stable) {
6183 conn.stableCount = 1;
6184 conn.numStableIncs = 1;
6185 } else {
6186 conn.unstableCount = 1;
6187 conn.numUnstableIncs = 1;
6188 }
6189 cpr.connections.add(conn);
6190 r.conProviders.add(conn);
6191 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006192 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006193 cpr.addExternalProcessHandleLocked(externalProcessToken);
6194 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006195 }
6196
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006197 boolean decProviderCountLocked(ContentProviderConnection conn,
6198 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6199 if (conn != null) {
6200 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006201 if (DEBUG_PROVIDER) Slog.v(TAG,
6202 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006203 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006204 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006205 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6206 if (stable) {
6207 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006208 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006209 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006210 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006211 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6212 cpr.connections.remove(conn);
6213 conn.client.conProviders.remove(conn);
6214 return true;
6215 }
6216 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006217 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006218 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006219 return false;
6220 }
6221
Amith Yamasani742a6712011-05-04 14:49:28 -07006222 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn41203752012-08-31 14:05:51 -07006223 String name, IBinder token, boolean stable, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006225 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 ProviderInfo cpi = null;
6227
6228 synchronized(this) {
6229 ProcessRecord r = null;
6230 if (caller != null) {
6231 r = getRecordForAppLocked(caller);
6232 if (r == null) {
6233 throw new SecurityException(
6234 "Unable to find app for caller " + caller
6235 + " (pid=" + Binder.getCallingPid()
6236 + ") when getting content provider " + name);
6237 }
Dianne Hackborn41203752012-08-31 14:05:51 -07006238 if (r.userId != userId) {
6239 throw new SecurityException("Calling requested user " + userId
6240 + " but app is user " + r.userId);
6241 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006242 }
6243
6244 // First check if this content provider has been published...
Amith Yamasani742a6712011-05-04 14:49:28 -07006245 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006246 boolean providerRunning = cpr != null;
6247 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006249 String msg;
6250 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6251 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 }
6253
6254 if (r != null && cpr.canRunHere(r)) {
6255 // This provider has been published or is in the process
6256 // of being published... but it is also allowed to run
6257 // in the caller's process, so don't make a connection
6258 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006259 ContentProviderHolder holder = cpr.newHolder(null);
6260 // don't give caller the provider object, it needs
6261 // to make its own.
6262 holder.provider = null;
6263 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 }
6265
6266 final long origId = Binder.clearCallingIdentity();
6267
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006268 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006270 conn = incProviderCountLocked(r, cpr, token, stable);
6271 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006272 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006273 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006274 // make sure to count it as being accessed and thus
6275 // back up on the LRU list. This is good because
6276 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006277 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006278 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006279 }
6280
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006281 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006282 if (false) {
6283 if (cpr.name.flattenToShortString().equals(
6284 "com.android.providers.calendar/.CalendarProvider2")) {
6285 Slog.v(TAG, "****************** KILLING "
6286 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006287 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006288 }
6289 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006290 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006291 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6292 // NOTE: there is still a race here where a signal could be
6293 // pending on the process even though we managed to update its
6294 // adj level. Not sure what to do about this, but at least
6295 // the race is now smaller.
6296 if (!success) {
6297 // Uh oh... it looks like the provider's process
6298 // has been killed on us. We need to wait for a new
6299 // process to be started, and make sure its death
6300 // doesn't kill our process.
6301 Slog.i(TAG,
6302 "Existing provider " + cpr.name.flattenToShortString()
6303 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006304 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006305 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006306 if (!lastRef) {
6307 // This wasn't the last ref our process had on
6308 // the provider... we have now been killed, bail.
6309 return null;
6310 }
6311 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006312 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 }
6315
6316 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006319 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006320 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006322 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006323 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006324 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 } catch (RemoteException ex) {
6326 }
6327 if (cpi == null) {
6328 return null;
6329 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006330 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6331 cpi.name, cpi.flags);
6332 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006333 userId = 0;
6334 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006335 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006336
Dianne Hackbornb424b632010-08-18 15:59:05 -07006337 String msg;
6338 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6339 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006340 }
6341
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006342 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006343 && !cpi.processName.equals("system")) {
6344 // If this content provider does not run in the system
6345 // process, and the system is not yet ready to run other
6346 // processes, then fail fast instead of hanging.
6347 throw new IllegalArgumentException(
6348 "Attempt to launch content provider before system ready");
6349 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006350
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006351 // Make sure that the user who owns this provider is started. If not,
6352 // we don't want to allow it to run.
6353 if (mStartedUsers.get(userId) == null) {
6354 Slog.w(TAG, "Unable to launch app "
6355 + cpi.applicationInfo.packageName + "/"
6356 + cpi.applicationInfo.uid + " for provider "
6357 + name + ": user " + userId + " is stopped");
6358 return null;
6359 }
6360
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006361 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006362 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 final boolean firstClass = cpr == null;
6364 if (firstClass) {
6365 try {
6366 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006367 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368 getApplicationInfo(
6369 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006370 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006372 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 + cpi.name);
6374 return null;
6375 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006376 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006377 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 } catch (RemoteException ex) {
6379 // pm is in same process, this will never happen.
6380 }
6381 }
6382
6383 if (r != null && cpr.canRunHere(r)) {
6384 // If this is a multiprocess provider, then just return its
6385 // info and allow the caller to instantiate it. Only do
6386 // this if the provider is the same user as the caller's
6387 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006388 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006389 }
6390
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006391 if (DEBUG_PROVIDER) {
6392 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006393 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006394 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 }
6396
6397 // This is single process, and our app is now connecting to it.
6398 // See if we are already in the process of launching this
6399 // provider.
6400 final int N = mLaunchingProviders.size();
6401 int i;
6402 for (i=0; i<N; i++) {
6403 if (mLaunchingProviders.get(i) == cpr) {
6404 break;
6405 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 }
6407
6408 // If the provider is not already being launched, then get it
6409 // started.
6410 if (i >= N) {
6411 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006412
6413 try {
6414 // Content provider is now in use, its package can't be stopped.
6415 try {
6416 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006417 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006418 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006419 } catch (IllegalArgumentException e) {
6420 Slog.w(TAG, "Failed trying to unstop package "
6421 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006422 }
6423
6424 ProcessRecord proc = startProcessLocked(cpi.processName,
6425 cpr.appInfo, false, 0, "content provider",
6426 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006427 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006428 if (proc == null) {
6429 Slog.w(TAG, "Unable to launch app "
6430 + cpi.applicationInfo.packageName + "/"
6431 + cpi.applicationInfo.uid + " for provider "
6432 + name + ": process is bad");
6433 return null;
6434 }
6435 cpr.launchingApp = proc;
6436 mLaunchingProviders.add(cpr);
6437 } finally {
6438 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006440 }
6441
6442 // Make sure the provider is published (the same provider class
6443 // may be published under multiple names).
6444 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006445 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006446 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006447
Amith Yamasani742a6712011-05-04 14:49:28 -07006448 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006449 conn = incProviderCountLocked(r, cpr, token, stable);
6450 if (conn != null) {
6451 conn.waiting = true;
6452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 }
6454 }
6455
6456 // Wait for the provider to be published...
6457 synchronized (cpr) {
6458 while (cpr.provider == null) {
6459 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006460 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006461 + cpi.applicationInfo.packageName + "/"
6462 + cpi.applicationInfo.uid + " for provider "
6463 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006464 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006465 cpi.applicationInfo.packageName,
6466 cpi.applicationInfo.uid, name);
6467 return null;
6468 }
6469 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006470 if (DEBUG_MU) {
6471 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6472 + cpr.launchingApp);
6473 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006474 if (conn != null) {
6475 conn.waiting = true;
6476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 cpr.wait();
6478 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006479 } finally {
6480 if (conn != null) {
6481 conn.waiting = false;
6482 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 }
6484 }
6485 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006486 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 }
6488
6489 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006490 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006491 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006492 if (caller == null) {
6493 String msg = "null IApplicationThread when getting content provider "
6494 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006495 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 throw new SecurityException(msg);
6497 }
6498
Dianne Hackborn41203752012-08-31 14:05:51 -07006499 return getContentProviderImpl(caller, name, null, stable,
6500 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006501 }
6502
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006503 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6504 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6505 "Do not have permission in call getContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006506 return getContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006507 }
6508
Dianne Hackborn41203752012-08-31 14:05:51 -07006509 private ContentProviderHolder getContentProviderExternalUnchecked(String name,
6510 IBinder token, int userId) {
6511 return getContentProviderImpl(null, name, token, true, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 }
6513
6514 /**
6515 * Drop a content provider from a ProcessRecord's bookkeeping
6516 * @param cpr
6517 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006518 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006519 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006521 ContentProviderConnection conn;
6522 try {
6523 conn = (ContentProviderConnection)connection;
6524 } catch (ClassCastException e) {
6525 String msg ="removeContentProvider: " + connection
6526 + " not a ContentProviderConnection";
6527 Slog.w(TAG, msg);
6528 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006530 if (conn == null) {
6531 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006532 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006533 if (decProviderCountLocked(conn, null, null, stable)) {
6534 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 }
6537 }
6538
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006539 public void removeContentProviderExternal(String name, IBinder token) {
6540 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6541 "Do not have permission in call removeContentProviderExternal()");
Dianne Hackborn41203752012-08-31 14:05:51 -07006542 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006543 }
6544
Dianne Hackborn41203752012-08-31 14:05:51 -07006545 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 synchronized (this) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006547 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 if(cpr == null) {
6549 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006550 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006551 return;
6552 }
6553
6554 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006555 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Dianne Hackborn41203752012-08-31 14:05:51 -07006556 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId);
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006557 if (localCpr.hasExternalProcessHandles()) {
6558 if (localCpr.removeExternalProcessHandleLocked(token)) {
6559 updateOomAdjLocked();
6560 } else {
6561 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6562 + " with no external reference for token: "
6563 + token + ".");
6564 }
6565 } else {
6566 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6567 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006569 }
6570 }
6571
6572 public final void publishContentProviders(IApplicationThread caller,
6573 List<ContentProviderHolder> providers) {
6574 if (providers == null) {
6575 return;
6576 }
6577
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006578 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006579 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006581 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006582 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 if (r == null) {
6584 throw new SecurityException(
6585 "Unable to find app for caller " + caller
6586 + " (pid=" + Binder.getCallingPid()
6587 + ") when publishing content providers");
6588 }
6589
6590 final long origId = Binder.clearCallingIdentity();
6591
6592 final int N = providers.size();
6593 for (int i=0; i<N; i++) {
6594 ContentProviderHolder src = providers.get(i);
6595 if (src == null || src.info == null || src.provider == null) {
6596 continue;
6597 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006598 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006599 if (DEBUG_MU)
6600 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006601 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006602 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006603 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 String names[] = dst.info.authority.split(";");
6605 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006606 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 }
6608
6609 int NL = mLaunchingProviders.size();
6610 int j;
6611 for (j=0; j<NL; j++) {
6612 if (mLaunchingProviders.get(j) == dst) {
6613 mLaunchingProviders.remove(j);
6614 j--;
6615 NL--;
6616 }
6617 }
6618 synchronized (dst) {
6619 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006620 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621 dst.notifyAll();
6622 }
6623 updateOomAdjLocked(r);
6624 }
6625 }
6626
6627 Binder.restoreCallingIdentity(origId);
6628 }
6629 }
6630
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006631 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6632 ContentProviderConnection conn;
6633 try {
6634 conn = (ContentProviderConnection)connection;
6635 } catch (ClassCastException e) {
6636 String msg ="refContentProvider: " + connection
6637 + " not a ContentProviderConnection";
6638 Slog.w(TAG, msg);
6639 throw new IllegalArgumentException(msg);
6640 }
6641 if (conn == null) {
6642 throw new NullPointerException("connection is null");
6643 }
6644
6645 synchronized (this) {
6646 if (stable > 0) {
6647 conn.numStableIncs += stable;
6648 }
6649 stable = conn.stableCount + stable;
6650 if (stable < 0) {
6651 throw new IllegalStateException("stableCount < 0: " + stable);
6652 }
6653
6654 if (unstable > 0) {
6655 conn.numUnstableIncs += unstable;
6656 }
6657 unstable = conn.unstableCount + unstable;
6658 if (unstable < 0) {
6659 throw new IllegalStateException("unstableCount < 0: " + unstable);
6660 }
6661
6662 if ((stable+unstable) <= 0) {
6663 throw new IllegalStateException("ref counts can't go to zero here: stable="
6664 + stable + " unstable=" + unstable);
6665 }
6666 conn.stableCount = stable;
6667 conn.unstableCount = unstable;
6668 return !conn.dead;
6669 }
6670 }
6671
6672 public void unstableProviderDied(IBinder connection) {
6673 ContentProviderConnection conn;
6674 try {
6675 conn = (ContentProviderConnection)connection;
6676 } catch (ClassCastException e) {
6677 String msg ="refContentProvider: " + connection
6678 + " not a ContentProviderConnection";
6679 Slog.w(TAG, msg);
6680 throw new IllegalArgumentException(msg);
6681 }
6682 if (conn == null) {
6683 throw new NullPointerException("connection is null");
6684 }
6685
6686 // Safely retrieve the content provider associated with the connection.
6687 IContentProvider provider;
6688 synchronized (this) {
6689 provider = conn.provider.provider;
6690 }
6691
6692 if (provider == null) {
6693 // Um, yeah, we're way ahead of you.
6694 return;
6695 }
6696
6697 // Make sure the caller is being honest with us.
6698 if (provider.asBinder().pingBinder()) {
6699 // Er, no, still looks good to us.
6700 synchronized (this) {
6701 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6702 + " says " + conn + " died, but we don't agree");
6703 return;
6704 }
6705 }
6706
6707 // Well look at that! It's dead!
6708 synchronized (this) {
6709 if (conn.provider.provider != provider) {
6710 // But something changed... good enough.
6711 return;
6712 }
6713
6714 ProcessRecord proc = conn.provider.proc;
6715 if (proc == null || proc.thread == null) {
6716 // Seems like the process is already cleaned up.
6717 return;
6718 }
6719
6720 // As far as we're concerned, this is just like receiving a
6721 // death notification... just a bit prematurely.
6722 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6723 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006724 final long ident = Binder.clearCallingIdentity();
6725 try {
6726 appDiedLocked(proc, proc.pid, proc.thread);
6727 } finally {
6728 Binder.restoreCallingIdentity(ident);
6729 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006730 }
6731 }
6732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006734 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006735 synchronized (mSelf) {
6736 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6737 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006738 if (providers != null) {
6739 for (int i=providers.size()-1; i>=0; i--) {
6740 ProviderInfo pi = (ProviderInfo)providers.get(i);
6741 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6742 Slog.w(TAG, "Not installing system proc provider " + pi.name
6743 + ": not system .apk");
6744 providers.remove(i);
6745 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006746 }
6747 }
6748 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006749 if (providers != null) {
6750 mSystemThread.installSystemProviders(providers);
6751 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006752
6753 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006754
6755 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006756 }
6757
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006758 /**
6759 * Allows app to retrieve the MIME type of a URI without having permission
6760 * to access its content provider.
6761 *
6762 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6763 *
6764 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6765 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6766 */
6767 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006768 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006769 final String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07006770 final int userId = UserHandle.getCallingUserId();
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006771 final long ident = Binder.clearCallingIdentity();
6772 ContentProviderHolder holder = null;
6773
6774 try {
Dianne Hackborn41203752012-08-31 14:05:51 -07006775 holder = getContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006776 if (holder != null) {
6777 return holder.provider.getType(uri);
6778 }
6779 } catch (RemoteException e) {
6780 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6781 return null;
6782 } finally {
6783 if (holder != null) {
Dianne Hackborn41203752012-08-31 14:05:51 -07006784 removeContentProviderExternalUnchecked(name, null, userId);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006785 }
6786 Binder.restoreCallingIdentity(ident);
6787 }
6788
6789 return null;
6790 }
6791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006792 // =========================================================
6793 // GLOBAL MANAGEMENT
6794 // =========================================================
6795
6796 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006797 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006798 String proc = customProcess != null ? customProcess : info.processName;
6799 BatteryStatsImpl.Uid.Proc ps = null;
6800 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006801 int uid = info.uid;
6802 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006803 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006804 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6805 uid = 0;
6806 while (true) {
6807 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6808 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6809 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6810 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006811 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006812 mNextIsolatedProcessUid++;
6813 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6814 // No process for this uid, use it.
6815 break;
6816 }
6817 stepsLeft--;
6818 if (stepsLeft <= 0) {
6819 return null;
6820 }
6821 }
6822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006823 synchronized (stats) {
6824 ps = stats.getProcessStatsLocked(info.uid, proc);
6825 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006826 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006827 }
6828
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006829 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6830 ProcessRecord app;
6831 if (!isolated) {
6832 app = getProcessRecordLocked(info.processName, info.uid);
6833 } else {
6834 app = null;
6835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836
6837 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006838 app = newProcessRecordLocked(null, info, null, isolated);
6839 mProcessNames.put(info.processName, app.uid, app);
6840 if (isolated) {
6841 mIsolatedProcesses.put(app.uid, app);
6842 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006843 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006844 }
6845
Dianne Hackborne7f97212011-02-24 14:40:20 -08006846 // This package really, really can not be stopped.
6847 try {
6848 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006849 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006850 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006851 } catch (IllegalArgumentException e) {
6852 Slog.w(TAG, "Failed trying to unstop package "
6853 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006854 }
6855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006856 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6857 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6858 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006859 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006860 }
6861 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6862 mPersistentStartingProcesses.add(app);
6863 startProcessLocked(app, "added application", app.processName);
6864 }
6865
6866 return app;
6867 }
6868
6869 public void unhandledBack() {
6870 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6871 "unhandledBack()");
6872
6873 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006874 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006875 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006876 TAG, "Performing unhandledBack(): stack size = " + count);
6877 if (count > 1) {
6878 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006879 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006880 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6881 Binder.restoreCallingIdentity(origId);
6882 }
6883 }
6884 }
6885
6886 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006887 enforceNotIsolatedCaller("openContentUri");
Dianne Hackborn41203752012-08-31 14:05:51 -07006888 final int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006889 String name = uri.getAuthority();
Dianne Hackborn41203752012-08-31 14:05:51 -07006890 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006891 ParcelFileDescriptor pfd = null;
6892 if (cph != null) {
6893 // We record the binder invoker's uid in thread-local storage before
6894 // going to the content provider to open the file. Later, in the code
6895 // that handles all permissions checks, we look for this uid and use
6896 // that rather than the Activity Manager's own uid. The effect is that
6897 // we do the check against the caller's permissions even though it looks
6898 // to the content provider like the Activity Manager itself is making
6899 // the request.
6900 sCallerIdentity.set(new Identity(
6901 Binder.getCallingPid(), Binder.getCallingUid()));
6902 try {
6903 pfd = cph.provider.openFile(uri, "r");
6904 } catch (FileNotFoundException e) {
6905 // do nothing; pfd will be returned null
6906 } finally {
6907 // Ensure that whatever happens, we clean up the identity state
6908 sCallerIdentity.remove();
6909 }
6910
6911 // We've got the fd now, so we're done with the provider.
Dianne Hackborn41203752012-08-31 14:05:51 -07006912 removeContentProviderExternalUnchecked(name, null, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006913 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006914 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006915 }
6916 return pfd;
6917 }
6918
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006919 // Actually is sleeping or shutting down or whatever else in the future
6920 // is an inactive state.
6921 public boolean isSleeping() {
6922 return mSleeping || mShuttingDown;
6923 }
6924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006925 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006926 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6927 != PackageManager.PERMISSION_GRANTED) {
6928 throw new SecurityException("Requires permission "
6929 + android.Manifest.permission.DEVICE_POWER);
6930 }
6931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006932 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006933 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006934 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006935
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006936 if (!mSleeping) {
6937 mSleeping = true;
6938 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006939
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006940 // Initialize the wake times of all processes.
6941 checkExcessivePowerUsageLocked(false);
6942 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6943 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6944 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006946 }
6947 }
6948
Dianne Hackborn55280a92009-05-07 15:53:46 -07006949 public boolean shutdown(int timeout) {
6950 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6951 != PackageManager.PERMISSION_GRANTED) {
6952 throw new SecurityException("Requires permission "
6953 + android.Manifest.permission.SHUTDOWN);
6954 }
6955
6956 boolean timedout = false;
6957
6958 synchronized(this) {
6959 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006960 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006961
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006962 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006963 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006964 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006965 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006966 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006967 long delay = endTime - System.currentTimeMillis();
6968 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006969 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006970 timedout = true;
6971 break;
6972 }
6973 try {
6974 this.wait();
6975 } catch (InterruptedException e) {
6976 }
6977 }
6978 }
6979 }
6980
6981 mUsageStatsService.shutdown();
6982 mBatteryStatsService.shutdown();
6983
6984 return timedout;
6985 }
6986
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006987 public final void activitySlept(IBinder token) {
6988 if (localLOGV) Slog.v(
6989 TAG, "Activity slept: token=" + token);
6990
6991 ActivityRecord r = null;
6992
6993 final long origId = Binder.clearCallingIdentity();
6994
6995 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006996 r = mMainStack.isInStackLocked(token);
6997 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006998 mMainStack.activitySleptLocked(r);
6999 }
7000 }
7001
7002 Binder.restoreCallingIdentity(origId);
7003 }
7004
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007005 private void comeOutOfSleepIfNeededLocked() {
7006 if (!mWentToSleep && !mLockScreenShown) {
7007 if (mSleeping) {
7008 mSleeping = false;
7009 mMainStack.awakeFromSleepingLocked();
7010 mMainStack.resumeTopActivityLocked(null);
7011 }
7012 }
7013 }
7014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007016 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7017 != PackageManager.PERMISSION_GRANTED) {
7018 throw new SecurityException("Requires permission "
7019 + android.Manifest.permission.DEVICE_POWER);
7020 }
7021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007023 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007024 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007025 comeOutOfSleepIfNeededLocked();
7026 }
7027 }
7028
Jeff Brownc042ee22012-05-08 13:03:42 -07007029 private void updateEventDispatchingLocked() {
7030 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7031 }
7032
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007033 public void setLockScreenShown(boolean shown) {
7034 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7035 != PackageManager.PERMISSION_GRANTED) {
7036 throw new SecurityException("Requires permission "
7037 + android.Manifest.permission.DEVICE_POWER);
7038 }
7039
7040 synchronized(this) {
7041 mLockScreenShown = shown;
7042 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 }
7044 }
7045
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007046 public void stopAppSwitches() {
7047 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7048 != PackageManager.PERMISSION_GRANTED) {
7049 throw new SecurityException("Requires permission "
7050 + android.Manifest.permission.STOP_APP_SWITCHES);
7051 }
7052
7053 synchronized(this) {
7054 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7055 + APP_SWITCH_DELAY_TIME;
7056 mDidAppSwitch = false;
7057 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7058 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7059 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7060 }
7061 }
7062
7063 public void resumeAppSwitches() {
7064 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7065 != PackageManager.PERMISSION_GRANTED) {
7066 throw new SecurityException("Requires permission "
7067 + android.Manifest.permission.STOP_APP_SWITCHES);
7068 }
7069
7070 synchronized(this) {
7071 // Note that we don't execute any pending app switches... we will
7072 // let those wait until either the timeout, or the next start
7073 // activity request.
7074 mAppSwitchesAllowedTime = 0;
7075 }
7076 }
7077
7078 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7079 String name) {
7080 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7081 return true;
7082 }
7083
7084 final int perm = checkComponentPermission(
7085 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007086 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007087 if (perm == PackageManager.PERMISSION_GRANTED) {
7088 return true;
7089 }
7090
Joe Onorato8a9b2202010-02-26 18:56:32 -08007091 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007092 return false;
7093 }
7094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007095 public void setDebugApp(String packageName, boolean waitForDebugger,
7096 boolean persistent) {
7097 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7098 "setDebugApp()");
7099
7100 // Note that this is not really thread safe if there are multiple
7101 // callers into it at the same time, but that's not a situation we
7102 // care about.
7103 if (persistent) {
7104 final ContentResolver resolver = mContext.getContentResolver();
7105 Settings.System.putString(
7106 resolver, Settings.System.DEBUG_APP,
7107 packageName);
7108 Settings.System.putInt(
7109 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7110 waitForDebugger ? 1 : 0);
7111 }
7112
7113 synchronized (this) {
7114 if (!persistent) {
7115 mOrigDebugApp = mDebugApp;
7116 mOrigWaitForDebugger = mWaitForDebugger;
7117 }
7118 mDebugApp = packageName;
7119 mWaitForDebugger = waitForDebugger;
7120 mDebugTransient = !persistent;
7121 if (packageName != null) {
7122 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07007123 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007124 Binder.restoreCallingIdentity(origId);
7125 }
7126 }
7127 }
7128
Siva Velusamy92a8b222012-03-09 16:24:04 -08007129 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7130 synchronized (this) {
7131 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7132 if (!isDebuggable) {
7133 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7134 throw new SecurityException("Process not debuggable: " + app.packageName);
7135 }
7136 }
7137
7138 mOpenGlTraceApp = processName;
7139 }
7140 }
7141
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007142 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7143 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7144 synchronized (this) {
7145 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7146 if (!isDebuggable) {
7147 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7148 throw new SecurityException("Process not debuggable: " + app.packageName);
7149 }
7150 }
7151 mProfileApp = processName;
7152 mProfileFile = profileFile;
7153 if (mProfileFd != null) {
7154 try {
7155 mProfileFd.close();
7156 } catch (IOException e) {
7157 }
7158 mProfileFd = null;
7159 }
7160 mProfileFd = profileFd;
7161 mProfileType = 0;
7162 mAutoStopProfiler = autoStopProfiler;
7163 }
7164 }
7165
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007166 public void setAlwaysFinish(boolean enabled) {
7167 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7168 "setAlwaysFinish()");
7169
7170 Settings.System.putInt(
7171 mContext.getContentResolver(),
7172 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7173
7174 synchronized (this) {
7175 mAlwaysFinishActivities = enabled;
7176 }
7177 }
7178
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007179 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007180 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007181 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007182 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007183 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007184 }
7185 }
7186
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007187 public boolean isUserAMonkey() {
7188 // For now the fact that there is a controller implies
7189 // we have a monkey.
7190 synchronized (this) {
7191 return mController != null;
7192 }
7193 }
7194
Jeff Sharkeya4620792011-05-20 15:29:23 -07007195 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007196 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7197 "registerProcessObserver()");
7198 synchronized (this) {
7199 mProcessObservers.register(observer);
7200 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007201 }
7202
7203 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007204 synchronized (this) {
7205 mProcessObservers.unregister(observer);
7206 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007207 }
7208
Daniel Sandler69a48172010-06-23 16:29:36 -04007209 public void setImmersive(IBinder token, boolean immersive) {
7210 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007211 ActivityRecord r = mMainStack.isInStackLocked(token);
7212 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007213 throw new IllegalArgumentException();
7214 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007215 r.immersive = immersive;
7216 }
7217 }
7218
7219 public boolean isImmersive(IBinder token) {
7220 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007221 ActivityRecord r = mMainStack.isInStackLocked(token);
7222 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007223 throw new IllegalArgumentException();
7224 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007225 return r.immersive;
7226 }
7227 }
7228
7229 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007230 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007231 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007232 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007233 return (r != null) ? r.immersive : false;
7234 }
7235 }
7236
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007237 public final void enterSafeMode() {
7238 synchronized(this) {
7239 // It only makes sense to do this before the system is ready
7240 // and started launching other packages.
7241 if (!mSystemReady) {
7242 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007243 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007244 } catch (RemoteException e) {
7245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007246 }
7247 }
7248 }
7249
Jeff Brownb09abc12011-01-13 21:08:27 -08007250 public final void showSafeModeOverlay() {
7251 View v = LayoutInflater.from(mContext).inflate(
7252 com.android.internal.R.layout.safe_mode, null);
7253 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7254 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7255 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7256 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007257 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007258 lp.format = v.getBackground().getOpacity();
7259 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7260 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7261 ((WindowManager)mContext.getSystemService(
7262 Context.WINDOW_SERVICE)).addView(v, lp);
7263 }
7264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265 public void noteWakeupAlarm(IIntentSender sender) {
7266 if (!(sender instanceof PendingIntentRecord)) {
7267 return;
7268 }
7269 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7270 synchronized (stats) {
7271 if (mBatteryStatsService.isOnBattery()) {
7272 mBatteryStatsService.enforceCallingPermission();
7273 PendingIntentRecord rec = (PendingIntentRecord)sender;
7274 int MY_UID = Binder.getCallingUid();
7275 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7276 BatteryStatsImpl.Uid.Pkg pkg =
7277 stats.getPackageStatsLocked(uid, rec.key.packageName);
7278 pkg.incWakeupsLocked();
7279 }
7280 }
7281 }
7282
Dianne Hackborn64825172011-03-02 21:32:58 -08007283 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007285 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007286 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007287 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007288 // XXX Note: don't acquire main activity lock here, because the window
7289 // manager calls in with its locks held.
7290
7291 boolean killed = false;
7292 synchronized (mPidsSelfLocked) {
7293 int[] types = new int[pids.length];
7294 int worstType = 0;
7295 for (int i=0; i<pids.length; i++) {
7296 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7297 if (proc != null) {
7298 int type = proc.setAdj;
7299 types[i] = type;
7300 if (type > worstType) {
7301 worstType = type;
7302 }
7303 }
7304 }
7305
Dianne Hackborn64825172011-03-02 21:32:58 -08007306 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007307 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007308 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7309 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007310 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007311 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007312
7313 // If this is not a secure call, don't let it kill processes that
7314 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007315 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7316 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007317 }
7318
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007319 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007320 for (int i=0; i<pids.length; i++) {
7321 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7322 if (proc == null) {
7323 continue;
7324 }
7325 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007326 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007327 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007328 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7329 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007330 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007331 proc.killedBackground = true;
7332 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007333 }
7334 }
7335 }
7336 return killed;
7337 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007338
7339 @Override
7340 public boolean killProcessesBelowForeground(String reason) {
7341 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7342 throw new SecurityException("killProcessesBelowForeground() only available to system");
7343 }
7344
7345 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7346 }
7347
7348 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7349 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7350 throw new SecurityException("killProcessesBelowAdj() only available to system");
7351 }
7352
7353 boolean killed = false;
7354 synchronized (mPidsSelfLocked) {
7355 final int size = mPidsSelfLocked.size();
7356 for (int i = 0; i < size; i++) {
7357 final int pid = mPidsSelfLocked.keyAt(i);
7358 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7359 if (proc == null) continue;
7360
7361 final int adj = proc.setAdj;
7362 if (adj > belowAdj && !proc.killedBackground) {
7363 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7364 EventLog.writeEvent(
7365 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7366 killed = true;
7367 proc.killedBackground = true;
7368 Process.killProcessQuiet(pid);
7369 }
7370 }
7371 }
7372 return killed;
7373 }
7374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007375 public final void startRunning(String pkg, String cls, String action,
7376 String data) {
7377 synchronized(this) {
7378 if (mStartRunning) {
7379 return;
7380 }
7381 mStartRunning = true;
7382 mTopComponent = pkg != null && cls != null
7383 ? new ComponentName(pkg, cls) : null;
7384 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7385 mTopData = data;
7386 if (!mSystemReady) {
7387 return;
7388 }
7389 }
7390
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007391 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007392 }
7393
7394 private void retrieveSettings() {
7395 final ContentResolver resolver = mContext.getContentResolver();
7396 String debugApp = Settings.System.getString(
7397 resolver, Settings.System.DEBUG_APP);
7398 boolean waitForDebugger = Settings.System.getInt(
7399 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7400 boolean alwaysFinishActivities = Settings.System.getInt(
7401 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7402
7403 Configuration configuration = new Configuration();
7404 Settings.System.getConfiguration(resolver, configuration);
7405
7406 synchronized (this) {
7407 mDebugApp = mOrigDebugApp = debugApp;
7408 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7409 mAlwaysFinishActivities = alwaysFinishActivities;
7410 // This happens before any activities are started, so we can
7411 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007412 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007413 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007414 }
7415 }
7416
7417 public boolean testIsSystemReady() {
7418 // no need to synchronize(this) just to read & return the value
7419 return mSystemReady;
7420 }
7421
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007422 private static File getCalledPreBootReceiversFile() {
7423 File dataDir = Environment.getDataDirectory();
7424 File systemDir = new File(dataDir, "system");
7425 File fname = new File(systemDir, "called_pre_boots.dat");
7426 return fname;
7427 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007428
7429 static final int LAST_DONE_VERSION = 10000;
7430
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007431 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7432 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7433 File file = getCalledPreBootReceiversFile();
7434 FileInputStream fis = null;
7435 try {
7436 fis = new FileInputStream(file);
7437 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007438 int fvers = dis.readInt();
7439 if (fvers == LAST_DONE_VERSION) {
7440 String vers = dis.readUTF();
7441 String codename = dis.readUTF();
7442 String build = dis.readUTF();
7443 if (android.os.Build.VERSION.RELEASE.equals(vers)
7444 && android.os.Build.VERSION.CODENAME.equals(codename)
7445 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7446 int num = dis.readInt();
7447 while (num > 0) {
7448 num--;
7449 String pkg = dis.readUTF();
7450 String cls = dis.readUTF();
7451 lastDoneReceivers.add(new ComponentName(pkg, cls));
7452 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007453 }
7454 }
7455 } catch (FileNotFoundException e) {
7456 } catch (IOException e) {
7457 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7458 } finally {
7459 if (fis != null) {
7460 try {
7461 fis.close();
7462 } catch (IOException e) {
7463 }
7464 }
7465 }
7466 return lastDoneReceivers;
7467 }
7468
7469 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7470 File file = getCalledPreBootReceiversFile();
7471 FileOutputStream fos = null;
7472 DataOutputStream dos = null;
7473 try {
7474 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7475 fos = new FileOutputStream(file);
7476 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007477 dos.writeInt(LAST_DONE_VERSION);
7478 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007479 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007480 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007481 dos.writeInt(list.size());
7482 for (int i=0; i<list.size(); i++) {
7483 dos.writeUTF(list.get(i).getPackageName());
7484 dos.writeUTF(list.get(i).getClassName());
7485 }
7486 } catch (IOException e) {
7487 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7488 file.delete();
7489 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007490 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007491 if (dos != null) {
7492 try {
7493 dos.close();
7494 } catch (IOException e) {
7495 // TODO Auto-generated catch block
7496 e.printStackTrace();
7497 }
7498 }
7499 }
7500 }
7501
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007502 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007503 synchronized(this) {
7504 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007505 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007506 return;
7507 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007508
7509 // Check to see if there are any update receivers to run.
7510 if (!mDidUpdate) {
7511 if (mWaitingUpdate) {
7512 return;
7513 }
7514 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7515 List<ResolveInfo> ris = null;
7516 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007517 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007518 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007519 } catch (RemoteException e) {
7520 }
7521 if (ris != null) {
7522 for (int i=ris.size()-1; i>=0; i--) {
7523 if ((ris.get(i).activityInfo.applicationInfo.flags
7524 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7525 ris.remove(i);
7526 }
7527 }
7528 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007529
7530 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7531
7532 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007533 for (int i=0; i<ris.size(); i++) {
7534 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007535 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7536 if (lastDoneReceivers.contains(comp)) {
7537 ris.remove(i);
7538 i--;
7539 }
7540 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007541
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007542 for (int i=0; i<ris.size(); i++) {
7543 ActivityInfo ai = ris.get(i).activityInfo;
7544 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7545 doneReceivers.add(comp);
7546 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007547 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007548 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007549 finisher = new IIntentReceiver.Stub() {
7550 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007551 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007552 boolean sticky) {
7553 // The raw IIntentReceiver interface is called
7554 // with the AM lock held, so redispatch to
7555 // execute our code without the lock.
7556 mHandler.post(new Runnable() {
7557 public void run() {
7558 synchronized (ActivityManagerService.this) {
7559 mDidUpdate = true;
7560 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007561 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007562 showBootMessage(mContext.getText(
7563 R.string.android_upgrading_complete),
7564 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007565 systemReady(goingCallback);
7566 }
7567 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007568 }
7569 };
7570 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007571 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007572 // XXX also need to send this to stopped users(!!!)
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007573 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007574 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007575 UserHandle.USER_ALL);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007576 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007577 mWaitingUpdate = true;
7578 }
7579 }
7580 }
7581 if (mWaitingUpdate) {
7582 return;
7583 }
7584 mDidUpdate = true;
7585 }
7586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 mSystemReady = true;
7588 if (!mStartRunning) {
7589 return;
7590 }
7591 }
7592
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007593 ArrayList<ProcessRecord> procsToKill = null;
7594 synchronized(mPidsSelfLocked) {
7595 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7596 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7597 if (!isAllowedWhileBooting(proc.info)){
7598 if (procsToKill == null) {
7599 procsToKill = new ArrayList<ProcessRecord>();
7600 }
7601 procsToKill.add(proc);
7602 }
7603 }
7604 }
7605
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007606 synchronized(this) {
7607 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007608 for (int i=procsToKill.size()-1; i>=0; i--) {
7609 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007610 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007611 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007612 }
7613 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007614
7615 // Now that we have cleaned up any update processes, we
7616 // are ready to start launching real processes and know that
7617 // we won't trample on them any more.
7618 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007619 }
7620
Joe Onorato8a9b2202010-02-26 18:56:32 -08007621 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007622 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007623 SystemClock.uptimeMillis());
7624
7625 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007626 // Make sure we have no pre-ready processes sitting around.
7627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007628 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7629 ResolveInfo ri = mContext.getPackageManager()
7630 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007631 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 CharSequence errorMsg = null;
7633 if (ri != null) {
7634 ActivityInfo ai = ri.activityInfo;
7635 ApplicationInfo app = ai.applicationInfo;
7636 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7637 mTopAction = Intent.ACTION_FACTORY_TEST;
7638 mTopData = null;
7639 mTopComponent = new ComponentName(app.packageName,
7640 ai.name);
7641 } else {
7642 errorMsg = mContext.getResources().getText(
7643 com.android.internal.R.string.factorytest_not_system);
7644 }
7645 } else {
7646 errorMsg = mContext.getResources().getText(
7647 com.android.internal.R.string.factorytest_no_action);
7648 }
7649 if (errorMsg != null) {
7650 mTopAction = null;
7651 mTopData = null;
7652 mTopComponent = null;
7653 Message msg = Message.obtain();
7654 msg.what = SHOW_FACTORY_ERROR_MSG;
7655 msg.getData().putCharSequence("msg", errorMsg);
7656 mHandler.sendMessage(msg);
7657 }
7658 }
7659 }
7660
7661 retrieveSettings();
7662
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007663 if (goingCallback != null) goingCallback.run();
7664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007665 synchronized (this) {
7666 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7667 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007668 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007669 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670 if (apps != null) {
7671 int N = apps.size();
7672 int i;
7673 for (i=0; i<N; i++) {
7674 ApplicationInfo info
7675 = (ApplicationInfo)apps.get(i);
7676 if (info != null &&
7677 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007678 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679 }
7680 }
7681 }
7682 } catch (RemoteException ex) {
7683 // pm is in same process, this will never happen.
7684 }
7685 }
7686
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007687 // Start up initial activity.
7688 mBooting = true;
7689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007691 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 Message msg = Message.obtain();
7693 msg.what = SHOW_UID_ERROR_MSG;
7694 mHandler.sendMessage(msg);
7695 }
7696 } catch (RemoteException e) {
7697 }
7698
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007699 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007700 }
7701 }
7702
Dan Egnorb7f03672009-12-09 16:22:32 -08007703 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007704 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007705 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007706 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007707 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 startAppProblemLocked(app);
7709 app.stopFreezingAllLocked();
7710 return handleAppCrashLocked(app);
7711 }
7712
Dan Egnorb7f03672009-12-09 16:22:32 -08007713 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007714 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007716 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007717 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7718 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007719 startAppProblemLocked(app);
7720 app.stopFreezingAllLocked();
7721 }
7722
7723 /**
7724 * Generate a process error record, suitable for attachment to a ProcessRecord.
7725 *
7726 * @param app The ProcessRecord in which the error occurred.
7727 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7728 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007729 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 * @param shortMsg Short message describing the crash.
7731 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007732 * @param stackTrace Full crash stack trace, may be null.
7733 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007734 * @return Returns a fully-formed AppErrorStateInfo record.
7735 */
7736 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007737 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 report.condition = condition;
7741 report.processName = app.processName;
7742 report.pid = app.pid;
7743 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007744 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007745 report.shortMsg = shortMsg;
7746 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007747 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748
7749 return report;
7750 }
7751
Dan Egnor42471dd2010-01-07 17:25:22 -08007752 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753 synchronized (this) {
7754 app.crashing = false;
7755 app.crashingReport = null;
7756 app.notResponding = false;
7757 app.notRespondingReport = null;
7758 if (app.anrDialog == fromDialog) {
7759 app.anrDialog = null;
7760 }
7761 if (app.waitDialog == fromDialog) {
7762 app.waitDialog = null;
7763 }
7764 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007765 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007766 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007767 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7768 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007769 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007770 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 }
7772 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007773
Dan Egnorb7f03672009-12-09 16:22:32 -08007774 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007775 if (mHeadless) {
7776 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7777 return false;
7778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 long now = SystemClock.uptimeMillis();
7780
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007781 Long crashTime;
7782 if (!app.isolated) {
7783 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7784 } else {
7785 crashTime = null;
7786 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007787 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007789 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007790 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007791 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007792 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007793 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7794 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007796 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007797 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007798 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007799 }
7800 }
7801 if (!app.persistent) {
7802 // We don't want to start this process again until the user
7803 // explicitly does so... but for persistent process, we really
7804 // need to keep it running. If a persistent process is actually
7805 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007806 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007808 if (!app.isolated) {
7809 // XXX We don't have a way to mark isolated processes
7810 // as bad, since they don't have a peristent identity.
7811 mBadProcesses.put(app.info.processName, app.uid, now);
7812 mProcessCrashTimes.remove(app.info.processName, app.uid);
7813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007814 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007816 // Don't let services in this process be restarted and potentially
7817 // annoy the user repeatedly. Unless it is persistent, since those
7818 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007819 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007820 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007821 return false;
7822 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007823 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007824 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007825 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007826 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007827 // If the top running activity is from this crashing
7828 // process, then terminate it to avoid getting in a loop.
7829 Slog.w(TAG, " Force finishing activity "
7830 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007831 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007832 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007833 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007834 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007835 // stopped, to avoid a situation where one will get
7836 // re-start our crashing activity once it gets resumed again.
7837 index--;
7838 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007839 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007840 if (r.state == ActivityState.RESUMED
7841 || r.state == ActivityState.PAUSING
7842 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007843 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007844 Slog.w(TAG, " Force finishing activity "
7845 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007846 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007847 Activity.RESULT_CANCELED, null, "crashed");
7848 }
7849 }
7850 }
7851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 }
7853
7854 // Bump up the crash count of any services currently running in the proc.
7855 if (app.services.size() != 0) {
7856 // Any services running in the application need to be placed
7857 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007858 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007859 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007860 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 sr.crashCount++;
7862 }
7863 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007864
7865 // If the crashing process is what we consider to be the "home process" and it has been
7866 // replaced by a third-party app, clear the package preferred activities from packages
7867 // with a home activity running in the process to prevent a repeatedly crashing app
7868 // from blocking the user to manually clear the list.
7869 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7870 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7871 Iterator it = mHomeProcess.activities.iterator();
7872 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007873 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007874 if (r.isHomeActivity) {
7875 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7876 try {
7877 ActivityThread.getPackageManager()
7878 .clearPackagePreferredActivities(r.packageName);
7879 } catch (RemoteException c) {
7880 // pm is in same process, this will never happen.
7881 }
7882 }
7883 }
7884 }
7885
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007886 if (!app.isolated) {
7887 // XXX Can't keep track of crash times for isolated processes,
7888 // because they don't have a perisistent identity.
7889 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7890 }
7891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007892 return true;
7893 }
7894
7895 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007896 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7897 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007898 skipCurrentReceiverLocked(app);
7899 }
7900
7901 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007902 for (BroadcastQueue queue : mBroadcastQueues) {
7903 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007904 }
7905 }
7906
Dan Egnor60d87622009-12-16 16:32:58 -08007907 /**
7908 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7909 * The application process will exit immediately after this call returns.
7910 * @param app object of the crashing app, null for the system server
7911 * @param crashInfo describing the exception
7912 */
7913 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007914 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007915 final String processName = app == null ? "system_server"
7916 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007917
7918 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007919 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007920 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007921 crashInfo.exceptionClassName,
7922 crashInfo.exceptionMessage,
7923 crashInfo.throwFileName,
7924 crashInfo.throwLineNumber);
7925
Jeff Sharkeya353d262011-10-28 11:12:06 -07007926 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007927
7928 crashApplication(r, crashInfo);
7929 }
7930
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007931 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007932 IBinder app,
7933 int violationMask,
7934 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007935 ProcessRecord r = findAppProcess(app, "StrictMode");
7936 if (r == null) {
7937 return;
7938 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007939
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007940 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007941 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007942 boolean logIt = true;
7943 synchronized (mAlreadyLoggedViolatedStacks) {
7944 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7945 logIt = false;
7946 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007947 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007948 // the relative pain numbers, without logging all
7949 // the stack traces repeatedly. We'd want to do
7950 // likewise in the client code, which also does
7951 // dup suppression, before the Binder call.
7952 } else {
7953 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7954 mAlreadyLoggedViolatedStacks.clear();
7955 }
7956 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7957 }
7958 }
7959 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007960 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007961 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007962 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007963
7964 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7965 AppErrorResult result = new AppErrorResult();
7966 synchronized (this) {
7967 final long origId = Binder.clearCallingIdentity();
7968
7969 Message msg = Message.obtain();
7970 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7971 HashMap<String, Object> data = new HashMap<String, Object>();
7972 data.put("result", result);
7973 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007974 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007975 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007976 msg.obj = data;
7977 mHandler.sendMessage(msg);
7978
7979 Binder.restoreCallingIdentity(origId);
7980 }
7981 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007982 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007983 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007984 }
7985
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007986 // Depending on the policy in effect, there could be a bunch of
7987 // these in quick succession so we try to batch these together to
7988 // minimize disk writes, number of dropbox entries, and maximize
7989 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007990 private void logStrictModeViolationToDropBox(
7991 ProcessRecord process,
7992 StrictMode.ViolationInfo info) {
7993 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007994 return;
7995 }
7996 final boolean isSystemApp = process == null ||
7997 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
7998 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07007999 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008000 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8001 final DropBoxManager dbox = (DropBoxManager)
8002 mContext.getSystemService(Context.DROPBOX_SERVICE);
8003
8004 // Exit early if the dropbox isn't configured to accept this report type.
8005 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8006
8007 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008008 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008009 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8010 synchronized (sb) {
8011 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008012 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008013 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8014 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008015 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8016 if (info.violationNumThisLoop != 0) {
8017 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8018 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008019 if (info.numAnimationsRunning != 0) {
8020 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8021 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008022 if (info.broadcastIntentAction != null) {
8023 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8024 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008025 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008026 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008027 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008028 if (info.numInstances != -1) {
8029 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8030 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008031 if (info.tags != null) {
8032 for (String tag : info.tags) {
8033 sb.append("Span-Tag: ").append(tag).append("\n");
8034 }
8035 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008036 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008037 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8038 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008039 }
8040 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008041
8042 // Only buffer up to ~64k. Various logging bits truncate
8043 // things at 128k.
8044 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008045 }
8046
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008047 // Flush immediately if the buffer's grown too large, or this
8048 // is a non-system app. Non-system apps are isolated with a
8049 // different tag & policy and not batched.
8050 //
8051 // Batching is useful during internal testing with
8052 // StrictMode settings turned up high. Without batching,
8053 // thousands of separate files could be created on boot.
8054 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008055 new Thread("Error dump: " + dropboxTag) {
8056 @Override
8057 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008058 String report;
8059 synchronized (sb) {
8060 report = sb.toString();
8061 sb.delete(0, sb.length());
8062 sb.trimToSize();
8063 }
8064 if (report.length() != 0) {
8065 dbox.addText(dropboxTag, report);
8066 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008067 }
8068 }.start();
8069 return;
8070 }
8071
8072 // System app batching:
8073 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008074 // An existing dropbox-writing thread is outstanding, so
8075 // we don't need to start it up. The existing thread will
8076 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008077 return;
8078 }
8079
8080 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8081 // (After this point, we shouldn't access AMS internal data structures.)
8082 new Thread("Error dump: " + dropboxTag) {
8083 @Override
8084 public void run() {
8085 // 5 second sleep to let stacks arrive and be batched together
8086 try {
8087 Thread.sleep(5000); // 5 seconds
8088 } catch (InterruptedException e) {}
8089
8090 String errorReport;
8091 synchronized (mStrictModeBuffer) {
8092 errorReport = mStrictModeBuffer.toString();
8093 if (errorReport.length() == 0) {
8094 return;
8095 }
8096 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8097 mStrictModeBuffer.trimToSize();
8098 }
8099 dbox.addText(dropboxTag, errorReport);
8100 }
8101 }.start();
8102 }
8103
Dan Egnor60d87622009-12-16 16:32:58 -08008104 /**
8105 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8106 * @param app object of the crashing app, null for the system server
8107 * @param tag reported by the caller
8108 * @param crashInfo describing the context of the error
8109 * @return true if the process should exit immediately (WTF is fatal)
8110 */
8111 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008112 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008113 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008114 final String processName = app == null ? "system_server"
8115 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008116
8117 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008118 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008119 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008120 tag, crashInfo.exceptionMessage);
8121
Jeff Sharkeya353d262011-10-28 11:12:06 -07008122 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008123
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008124 if (r != null && r.pid != Process.myPid() &&
8125 Settings.Secure.getInt(mContext.getContentResolver(),
8126 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008127 crashApplication(r, crashInfo);
8128 return true;
8129 } else {
8130 return false;
8131 }
8132 }
8133
8134 /**
8135 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8136 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8137 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008138 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008139 if (app == null) {
8140 return null;
8141 }
8142
8143 synchronized (this) {
8144 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8145 final int NA = apps.size();
8146 for (int ia=0; ia<NA; ia++) {
8147 ProcessRecord p = apps.valueAt(ia);
8148 if (p.thread != null && p.thread.asBinder() == app) {
8149 return p;
8150 }
8151 }
8152 }
8153
Dianne Hackborncb44d962011-03-10 17:02:27 -08008154 Slog.w(TAG, "Can't find mystery application for " + reason
8155 + " from pid=" + Binder.getCallingPid()
8156 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008157 return null;
8158 }
8159 }
8160
8161 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008162 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8163 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008164 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008165 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8166 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008167 // Watchdog thread ends up invoking this function (with
8168 // a null ProcessRecord) to add the stack file to dropbox.
8169 // Do not acquire a lock on this (am) in such cases, as it
8170 // could cause a potential deadlock, if and when watchdog
8171 // is invoked due to unavailability of lock on am and it
8172 // would prevent watchdog from killing system_server.
8173 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008174 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008175 return;
8176 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008177 // Note: ProcessRecord 'process' is guarded by the service
8178 // instance. (notably process.pkgList, which could otherwise change
8179 // concurrently during execution of this method)
8180 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008181 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008182 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008183 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008184 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8185 for (String pkg : process.pkgList) {
8186 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008187 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008188 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008189 if (pi != null) {
8190 sb.append(" v").append(pi.versionCode);
8191 if (pi.versionName != null) {
8192 sb.append(" (").append(pi.versionName).append(")");
8193 }
8194 }
8195 } catch (RemoteException e) {
8196 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008197 }
Dan Egnora455d192010-03-12 08:52:28 -08008198 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008199 }
Dan Egnora455d192010-03-12 08:52:28 -08008200 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008201 }
8202
8203 private static String processClass(ProcessRecord process) {
8204 if (process == null || process.pid == MY_PID) {
8205 return "system_server";
8206 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8207 return "system_app";
8208 } else {
8209 return "data_app";
8210 }
8211 }
8212
8213 /**
8214 * Write a description of an error (crash, WTF, ANR) to the drop box.
8215 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8216 * @param process which caused the error, null means the system server
8217 * @param activity which triggered the error, null if unknown
8218 * @param parent activity related to the error, null if unknown
8219 * @param subject line related to the error, null if absent
8220 * @param report in long form describing the error, null if absent
8221 * @param logFile to include in the report, null if none
8222 * @param crashInfo giving an application stack trace, null if absent
8223 */
8224 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008225 ProcessRecord process, String processName, ActivityRecord activity,
8226 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008227 final String report, final File logFile,
8228 final ApplicationErrorReport.CrashInfo crashInfo) {
8229 // NOTE -- this must never acquire the ActivityManagerService lock,
8230 // otherwise the watchdog may be prevented from resetting the system.
8231
8232 final String dropboxTag = processClass(process) + "_" + eventType;
8233 final DropBoxManager dbox = (DropBoxManager)
8234 mContext.getSystemService(Context.DROPBOX_SERVICE);
8235
8236 // Exit early if the dropbox isn't configured to accept this report type.
8237 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8238
8239 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008240 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008241 if (activity != null) {
8242 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8243 }
8244 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8245 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8246 }
8247 if (parent != null && parent != activity) {
8248 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8249 }
8250 if (subject != null) {
8251 sb.append("Subject: ").append(subject).append("\n");
8252 }
8253 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008254 if (Debug.isDebuggerConnected()) {
8255 sb.append("Debugger: Connected\n");
8256 }
Dan Egnora455d192010-03-12 08:52:28 -08008257 sb.append("\n");
8258
8259 // Do the rest in a worker thread to avoid blocking the caller on I/O
8260 // (After this point, we shouldn't access AMS internal data structures.)
8261 Thread worker = new Thread("Error dump: " + dropboxTag) {
8262 @Override
8263 public void run() {
8264 if (report != null) {
8265 sb.append(report);
8266 }
8267 if (logFile != null) {
8268 try {
8269 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8270 } catch (IOException e) {
8271 Slog.e(TAG, "Error reading " + logFile, e);
8272 }
8273 }
8274 if (crashInfo != null && crashInfo.stackTrace != null) {
8275 sb.append(crashInfo.stackTrace);
8276 }
8277
8278 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8279 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8280 if (lines > 0) {
8281 sb.append("\n");
8282
8283 // Merge several logcat streams, and take the last N lines
8284 InputStreamReader input = null;
8285 try {
8286 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8287 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8288 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8289
8290 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8291 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8292 input = new InputStreamReader(logcat.getInputStream());
8293
8294 int num;
8295 char[] buf = new char[8192];
8296 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8297 } catch (IOException e) {
8298 Slog.e(TAG, "Error running logcat", e);
8299 } finally {
8300 if (input != null) try { input.close(); } catch (IOException e) {}
8301 }
8302 }
8303
8304 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008305 }
Dan Egnora455d192010-03-12 08:52:28 -08008306 };
8307
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008308 if (process == null) {
8309 // If process is null, we are being called from some internal code
8310 // and may be about to die -- run this synchronously.
8311 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008312 } else {
8313 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008314 }
8315 }
8316
8317 /**
8318 * Bring up the "unexpected error" dialog box for a crashing app.
8319 * Deal with edge cases (intercepts from instrumented applications,
8320 * ActivityController, error intent receivers, that sort of thing).
8321 * @param r the application crashing
8322 * @param crashInfo describing the failure
8323 */
8324 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008325 long timeMillis = System.currentTimeMillis();
8326 String shortMsg = crashInfo.exceptionClassName;
8327 String longMsg = crashInfo.exceptionMessage;
8328 String stackTrace = crashInfo.stackTrace;
8329 if (shortMsg != null && longMsg != null) {
8330 longMsg = shortMsg + ": " + longMsg;
8331 } else if (shortMsg != null) {
8332 longMsg = shortMsg;
8333 }
8334
Dan Egnor60d87622009-12-16 16:32:58 -08008335 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008336 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008337 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338 try {
8339 String name = r != null ? r.processName : null;
8340 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008341 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008342 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008343 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008344 + " at watcher's request");
8345 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008346 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008347 }
8348 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008349 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008350 }
8351 }
8352
8353 final long origId = Binder.clearCallingIdentity();
8354
8355 // If this process is running instrumentation, finish it.
8356 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008357 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008358 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008359 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8360 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008361 Bundle info = new Bundle();
8362 info.putString("shortMsg", shortMsg);
8363 info.putString("longMsg", longMsg);
8364 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8365 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008366 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008367 }
8368
Dan Egnor60d87622009-12-16 16:32:58 -08008369 // If we can't identify the process or it's already exceeded its crash quota,
8370 // quit right away without showing a crash dialog.
8371 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008372 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008373 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008374 }
8375
8376 Message msg = Message.obtain();
8377 msg.what = SHOW_ERROR_MSG;
8378 HashMap data = new HashMap();
8379 data.put("result", result);
8380 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008381 msg.obj = data;
8382 mHandler.sendMessage(msg);
8383
8384 Binder.restoreCallingIdentity(origId);
8385 }
8386
8387 int res = result.get();
8388
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008389 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008390 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008391 if (r != null && !r.isolated) {
8392 // XXX Can't keep track of crash time for isolated processes,
8393 // since they don't have a persistent identity.
8394 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008395 SystemClock.uptimeMillis());
8396 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008397 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008398 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008399 }
8400 }
8401
8402 if (appErrorIntent != null) {
8403 try {
8404 mContext.startActivity(appErrorIntent);
8405 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008406 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008407 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008408 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008410
8411 Intent createAppErrorIntentLocked(ProcessRecord r,
8412 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8413 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008414 if (report == null) {
8415 return null;
8416 }
8417 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8418 result.setComponent(r.errorReportReceiver);
8419 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8420 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8421 return result;
8422 }
8423
Dan Egnorb7f03672009-12-09 16:22:32 -08008424 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8425 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008426 if (r.errorReportReceiver == null) {
8427 return null;
8428 }
8429
8430 if (!r.crashing && !r.notResponding) {
8431 return null;
8432 }
8433
Dan Egnorb7f03672009-12-09 16:22:32 -08008434 ApplicationErrorReport report = new ApplicationErrorReport();
8435 report.packageName = r.info.packageName;
8436 report.installerPackageName = r.errorReportReceiver.getPackageName();
8437 report.processName = r.processName;
8438 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008439 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008440
Dan Egnorb7f03672009-12-09 16:22:32 -08008441 if (r.crashing) {
8442 report.type = ApplicationErrorReport.TYPE_CRASH;
8443 report.crashInfo = crashInfo;
8444 } else if (r.notResponding) {
8445 report.type = ApplicationErrorReport.TYPE_ANR;
8446 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008447
Dan Egnorb7f03672009-12-09 16:22:32 -08008448 report.anrInfo.activity = r.notRespondingReport.tag;
8449 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8450 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008451 }
8452
Dan Egnorb7f03672009-12-09 16:22:32 -08008453 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008454 }
8455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008456 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008457 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008458 // assume our apps are happy - lazy create the list
8459 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8460
Dianne Hackborn0c380492012-08-20 17:23:30 -07008461 final boolean allUsers = ActivityManager.checkUidPermission(
8462 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8463 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8464 int userId = UserHandle.getUserId(Binder.getCallingUid());
8465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008466 synchronized (this) {
8467
8468 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008469 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8470 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008471 if (!allUsers && app.userId != userId) {
8472 continue;
8473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008474 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8475 // This one's in trouble, so we'll generate a report for it
8476 // crashes are higher priority (in case there's a crash *and* an anr)
8477 ActivityManager.ProcessErrorStateInfo report = null;
8478 if (app.crashing) {
8479 report = app.crashingReport;
8480 } else if (app.notResponding) {
8481 report = app.notRespondingReport;
8482 }
8483
8484 if (report != null) {
8485 if (errList == null) {
8486 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8487 }
8488 errList.add(report);
8489 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008490 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008491 " crashing = " + app.crashing +
8492 " notResponding = " + app.notResponding);
8493 }
8494 }
8495 }
8496 }
8497
8498 return errList;
8499 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008500
8501 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008502 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008503 if (currApp != null) {
8504 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8505 }
8506 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008507 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8508 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008509 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8510 if (currApp != null) {
8511 currApp.lru = 0;
8512 }
8513 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008514 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008515 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8516 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8517 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8518 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8519 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8520 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8521 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8522 } else {
8523 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8524 }
8525 }
8526
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008527 private void fillInProcMemInfo(ProcessRecord app,
8528 ActivityManager.RunningAppProcessInfo outInfo) {
8529 outInfo.pid = app.pid;
8530 outInfo.uid = app.info.uid;
8531 if (mHeavyWeightProcess == app) {
8532 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8533 }
8534 if (app.persistent) {
8535 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8536 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008537 if (app.hasActivities) {
8538 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8539 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008540 outInfo.lastTrimLevel = app.trimMemoryLevel;
8541 int adj = app.curAdj;
8542 outInfo.importance = oomAdjToImportance(adj, outInfo);
8543 outInfo.importanceReasonCode = app.adjTypeCode;
8544 }
8545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008546 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008547 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008548 // Lazy instantiation of list
8549 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008550 final boolean allUsers = ActivityManager.checkUidPermission(
8551 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8552 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8553 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 synchronized (this) {
8555 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008556 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8557 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008558 if (!allUsers && app.userId != userId) {
8559 continue;
8560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008561 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8562 // Generate process state info for running application
8563 ActivityManager.RunningAppProcessInfo currApp =
8564 new ActivityManager.RunningAppProcessInfo(app.processName,
8565 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008566 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008567 if (app.adjSource instanceof ProcessRecord) {
8568 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008569 currApp.importanceReasonImportance = oomAdjToImportance(
8570 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008571 } else if (app.adjSource instanceof ActivityRecord) {
8572 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008573 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8574 }
8575 if (app.adjTarget instanceof ComponentName) {
8576 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8577 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008578 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008579 // + " lru=" + currApp.lru);
8580 if (runList == null) {
8581 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8582 }
8583 runList.add(currApp);
8584 }
8585 }
8586 }
8587 return runList;
8588 }
8589
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008590 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008591 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008592 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8593 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8594 if (runningApps != null && runningApps.size() > 0) {
8595 Set<String> extList = new HashSet<String>();
8596 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8597 if (app.pkgList != null) {
8598 for (String pkg : app.pkgList) {
8599 extList.add(pkg);
8600 }
8601 }
8602 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008603 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008604 for (String pkg : extList) {
8605 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008606 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008607 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8608 retList.add(info);
8609 }
8610 } catch (RemoteException e) {
8611 }
8612 }
8613 }
8614 return retList;
8615 }
8616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008617 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008618 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8619 enforceNotIsolatedCaller("getMyMemoryState");
8620 synchronized (this) {
8621 ProcessRecord proc;
8622 synchronized (mPidsSelfLocked) {
8623 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8624 }
8625 fillInProcMemInfo(proc, outInfo);
8626 }
8627 }
8628
8629 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008630 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008631 if (checkCallingPermission(android.Manifest.permission.DUMP)
8632 != PackageManager.PERMISSION_GRANTED) {
8633 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8634 + Binder.getCallingPid()
8635 + ", uid=" + Binder.getCallingUid()
8636 + " without permission "
8637 + android.Manifest.permission.DUMP);
8638 return;
8639 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008640
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008641 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008642 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008643 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008644
8645 int opti = 0;
8646 while (opti < args.length) {
8647 String opt = args[opti];
8648 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8649 break;
8650 }
8651 opti++;
8652 if ("-a".equals(opt)) {
8653 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008654 } else if ("-c".equals(opt)) {
8655 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008656 } else if ("-h".equals(opt)) {
8657 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008658 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008659 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008660 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008661 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8662 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8663 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008664 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008665 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008666 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008667 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008668 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008669 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008670 pw.println(" all: dump all activities");
8671 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008672 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008673 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8674 pw.println(" a partial substring in a component name, a");
8675 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008676 pw.println(" -a: include all available server state.");
8677 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008679 } else {
8680 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008681 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008682 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008683
8684 long origId = Binder.clearCallingIdentity();
8685 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008686 // Is the caller requesting to dump a particular piece of data?
8687 if (opti < args.length) {
8688 String cmd = args[opti];
8689 opti++;
8690 if ("activities".equals(cmd) || "a".equals(cmd)) {
8691 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008692 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008693 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008694 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008695 String[] newArgs;
8696 String name;
8697 if (opti >= args.length) {
8698 name = null;
8699 newArgs = EMPTY_STRING_ARRAY;
8700 } else {
8701 name = args[opti];
8702 opti++;
8703 newArgs = new String[args.length - opti];
8704 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8705 args.length - opti);
8706 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008707 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008708 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008709 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008710 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008711 String[] newArgs;
8712 String name;
8713 if (opti >= args.length) {
8714 name = null;
8715 newArgs = EMPTY_STRING_ARRAY;
8716 } else {
8717 name = args[opti];
8718 opti++;
8719 newArgs = new String[args.length - opti];
8720 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8721 args.length - opti);
8722 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008723 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008724 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008725 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008726 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008727 String[] newArgs;
8728 String name;
8729 if (opti >= args.length) {
8730 name = null;
8731 newArgs = EMPTY_STRING_ARRAY;
8732 } else {
8733 name = args[opti];
8734 opti++;
8735 newArgs = new String[args.length - opti];
8736 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8737 args.length - opti);
8738 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008739 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008740 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008741 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008742 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8743 synchronized (this) {
8744 dumpOomLocked(fd, pw, args, opti, true);
8745 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008746 } else if ("provider".equals(cmd)) {
8747 String[] newArgs;
8748 String name;
8749 if (opti >= args.length) {
8750 name = null;
8751 newArgs = EMPTY_STRING_ARRAY;
8752 } else {
8753 name = args[opti];
8754 opti++;
8755 newArgs = new String[args.length - opti];
8756 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8757 }
8758 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8759 pw.println("No providers match: " + name);
8760 pw.println("Use -h for help.");
8761 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008762 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8763 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008764 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008765 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008766 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008767 String[] newArgs;
8768 String name;
8769 if (opti >= args.length) {
8770 name = null;
8771 newArgs = EMPTY_STRING_ARRAY;
8772 } else {
8773 name = args[opti];
8774 opti++;
8775 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008776 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8777 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008778 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008779 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008780 pw.println("No services match: " + name);
8781 pw.println("Use -h for help.");
8782 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008783 } else if ("package".equals(cmd)) {
8784 String[] newArgs;
8785 if (opti >= args.length) {
8786 pw.println("package: no package name specified");
8787 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008788 } else {
8789 dumpPackage = args[opti];
8790 opti++;
8791 newArgs = new String[args.length - opti];
8792 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8793 args.length - opti);
8794 args = newArgs;
8795 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008796 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008797 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008798 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8799 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008800 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008801 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008802 } else {
8803 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008804 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8805 pw.println("Bad activity command, or no activities match: " + cmd);
8806 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008807 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008808 }
8809 if (!more) {
8810 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008811 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008812 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008813 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008814
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008815 // No piece of data specified, dump everything.
8816 synchronized (this) {
8817 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008818 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008819 if (needSep) {
8820 pw.println(" ");
8821 }
8822 if (dumpAll) {
8823 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008824 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008825 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008826 if (needSep) {
8827 pw.println(" ");
8828 }
8829 if (dumpAll) {
8830 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008831 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008832 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008833 if (needSep) {
8834 pw.println(" ");
8835 }
8836 if (dumpAll) {
8837 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008838 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008839 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008840 if (needSep) {
8841 pw.println(" ");
8842 }
8843 if (dumpAll) {
8844 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008845 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008846 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008847 if (needSep) {
8848 pw.println(" ");
8849 }
8850 if (dumpAll) {
8851 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008852 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008853 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008854 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008855 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008856 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008857
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008858 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008859 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008860 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8861 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008862 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8863 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008864 pw.println(" ");
8865 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008866 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8867 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008868 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008869 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008870 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008871 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008872 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008873 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008874 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008875 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008876 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008877 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008878 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008879 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008880 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8881 pw.println(" ");
8882 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008883 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008884 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008885 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008886 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008887 pw.println(" ");
8888 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008889 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008890 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008893 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008894 if (mMainStack.mPausingActivity != null) {
8895 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008896 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008897 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008898 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008899 if (dumpAll) {
8900 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8901 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008902 pw.println(" mDismissKeyguardOnNextActivity: "
8903 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008905
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008906 if (mRecentTasks.size() > 0) {
8907 pw.println();
8908 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008909
8910 final int N = mRecentTasks.size();
8911 for (int i=0; i<N; i++) {
8912 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008913 if (dumpPackage != null) {
8914 if (tr.realActivity == null ||
8915 !dumpPackage.equals(tr.realActivity)) {
8916 continue;
8917 }
8918 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008919 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8920 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008921 if (dumpAll) {
8922 mRecentTasks.get(i).dump(pw, " ");
8923 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008924 }
8925 }
8926
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008927 if (dumpAll) {
8928 pw.println(" ");
8929 pw.println(" mCurTask: " + mCurTask);
8930 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008931
8932 return true;
8933 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008934
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008935 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008936 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008937 boolean needSep = false;
8938 int numPers = 0;
8939
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008940 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8941
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008942 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8944 final int NA = procs.size();
8945 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008946 ProcessRecord r = procs.valueAt(ia);
8947 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8948 continue;
8949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008950 if (!needSep) {
8951 pw.println(" All known processes:");
8952 needSep = true;
8953 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008954 pw.print(r.persistent ? " *PERS*" : " *APP*");
8955 pw.print(" UID "); pw.print(procs.keyAt(ia));
8956 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 r.dump(pw, " ");
8958 if (r.persistent) {
8959 numPers++;
8960 }
8961 }
8962 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008963 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008964
8965 if (mIsolatedProcesses.size() > 0) {
8966 if (needSep) pw.println(" ");
8967 needSep = true;
8968 pw.println(" Isolated process list (sorted by uid):");
8969 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8970 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8971 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8972 continue;
8973 }
8974 pw.println(String.format("%sIsolated #%2d: %s",
8975 " ", i, r.toString()));
8976 }
8977 }
8978
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008979 if (mLruProcesses.size() > 0) {
8980 if (needSep) pw.println(" ");
8981 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008982 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008983 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008984 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008985 needSep = true;
8986 }
8987
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008988 if (dumpAll) {
8989 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008990 boolean printed = false;
8991 for (int i=0; i<mPidsSelfLocked.size(); i++) {
8992 ProcessRecord r = mPidsSelfLocked.valueAt(i);
8993 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8994 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008995 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008996 if (!printed) {
8997 if (needSep) pw.println(" ");
8998 needSep = true;
8999 pw.println(" PID mappings:");
9000 printed = true;
9001 }
9002 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9003 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009004 }
9005 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009006 }
9007
9008 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009009 synchronized (mPidsSelfLocked) {
9010 boolean printed = false;
9011 for (int i=0; i<mForegroundProcesses.size(); i++) {
9012 ProcessRecord r = mPidsSelfLocked.get(
9013 mForegroundProcesses.valueAt(i).pid);
9014 if (dumpPackage != null && (r == null
9015 || !dumpPackage.equals(r.info.packageName))) {
9016 continue;
9017 }
9018 if (!printed) {
9019 if (needSep) pw.println(" ");
9020 needSep = true;
9021 pw.println(" Foreground Processes:");
9022 printed = true;
9023 }
9024 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9025 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9026 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009028 }
9029
9030 if (mPersistentStartingProcesses.size() > 0) {
9031 if (needSep) pw.println(" ");
9032 needSep = true;
9033 pw.println(" Persisent processes that are starting:");
9034 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009035 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009037
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009038 if (mRemovedProcesses.size() > 0) {
9039 if (needSep) pw.println(" ");
9040 needSep = true;
9041 pw.println(" Processes that are being removed:");
9042 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009043 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009044 }
9045
9046 if (mProcessesOnHold.size() > 0) {
9047 if (needSep) pw.println(" ");
9048 needSep = true;
9049 pw.println(" Processes that are on old until the system is ready:");
9050 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009051 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009053
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009054 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009055
9056 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009057 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009058 long now = SystemClock.uptimeMillis();
9059 for (Map.Entry<String, SparseArray<Long>> procs
9060 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009061 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009062 SparseArray<Long> uids = procs.getValue();
9063 final int N = uids.size();
9064 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009065 int puid = uids.keyAt(i);
9066 ProcessRecord r = mProcessNames.get(pname, puid);
9067 if (dumpPackage != null && (r == null
9068 || !dumpPackage.equals(r.info.packageName))) {
9069 continue;
9070 }
9071 if (!printed) {
9072 if (needSep) pw.println(" ");
9073 needSep = true;
9074 pw.println(" Time since processes crashed:");
9075 printed = true;
9076 }
9077 pw.print(" Process "); pw.print(pname);
9078 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009079 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009080 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9081 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009082 }
9083 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009085
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009086 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009087 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009088 for (Map.Entry<String, SparseArray<Long>> procs
9089 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009090 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009091 SparseArray<Long> uids = procs.getValue();
9092 final int N = uids.size();
9093 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009094 int puid = uids.keyAt(i);
9095 ProcessRecord r = mProcessNames.get(pname, puid);
9096 if (dumpPackage != null && (r == null
9097 || !dumpPackage.equals(r.info.packageName))) {
9098 continue;
9099 }
9100 if (!printed) {
9101 if (needSep) pw.println(" ");
9102 needSep = true;
9103 pw.println(" Bad processes:");
9104 }
9105 pw.print(" Bad process "); pw.print(pname);
9106 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009107 pw.print(": crashed at time ");
9108 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 }
9110 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009112
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009113 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009114 pw.println(" mStartedUsers:");
9115 for (int i=0; i<mStartedUsers.size(); i++) {
9116 UserStartedState uss = mStartedUsers.valueAt(i);
9117 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
9118 pw.println(":");
9119 uss.dump(" ", pw);
9120 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009121 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009122 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009123 if (dumpAll) {
9124 StringBuilder sb = new StringBuilder(128);
9125 sb.append(" mPreviousProcessVisibleTime: ");
9126 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9127 pw.println(sb);
9128 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009129 if (mHeavyWeightProcess != null) {
9130 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9131 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009132 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009133 if (dumpAll) {
9134 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009135 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009136 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009137 for (Map.Entry<String, Integer> entry
9138 : mCompatModePackages.getPackages().entrySet()) {
9139 String pkg = entry.getKey();
9140 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009141 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9142 continue;
9143 }
9144 if (!printed) {
9145 pw.println(" mScreenCompatPackages:");
9146 printed = true;
9147 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009148 pw.print(" "); pw.print(pkg); pw.print(": ");
9149 pw.print(mode); pw.println();
9150 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009151 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009152 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009153 if (mSleeping || mWentToSleep || mLockScreenShown) {
9154 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9155 + " mLockScreenShown " + mLockScreenShown);
9156 }
9157 if (mShuttingDown) {
9158 pw.println(" mShuttingDown=" + mShuttingDown);
9159 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009160 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9161 || mOrigWaitForDebugger) {
9162 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9163 + " mDebugTransient=" + mDebugTransient
9164 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9165 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009166 if (mOpenGlTraceApp != null) {
9167 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9168 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009169 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9170 || mProfileFd != null) {
9171 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9172 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9173 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9174 + mAutoStopProfiler);
9175 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009176 if (mAlwaysFinishActivities || mController != null) {
9177 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9178 + " mController=" + mController);
9179 }
9180 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009182 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009183 + " mProcessesReady=" + mProcessesReady
9184 + " mSystemReady=" + mSystemReady);
9185 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009186 + " mBooted=" + mBooted
9187 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009188 pw.print(" mLastPowerCheckRealtime=");
9189 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9190 pw.println("");
9191 pw.print(" mLastPowerCheckUptime=");
9192 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9193 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009194 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9195 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009196 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009197 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9198 + " mNumHiddenProcs=" + mNumHiddenProcs
9199 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009200 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009201 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009202
9203 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009204 }
9205
Dianne Hackborn287952c2010-09-22 22:34:31 -07009206 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009207 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009208 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009209 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009210 long now = SystemClock.uptimeMillis();
9211 for (int i=0; i<mProcessesToGc.size(); i++) {
9212 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009213 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9214 continue;
9215 }
9216 if (!printed) {
9217 if (needSep) pw.println(" ");
9218 needSep = true;
9219 pw.println(" Processes that are waiting to GC:");
9220 printed = true;
9221 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009222 pw.print(" Process "); pw.println(proc);
9223 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9224 pw.print(", last gced=");
9225 pw.print(now-proc.lastRequestedGc);
9226 pw.print(" ms ago, last lowMem=");
9227 pw.print(now-proc.lastLowMemory);
9228 pw.println(" ms ago");
9229
9230 }
9231 }
9232 return needSep;
9233 }
9234
9235 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9236 int opti, boolean dumpAll) {
9237 boolean needSep = false;
9238
9239 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009240 if (needSep) pw.println(" ");
9241 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009242 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009243 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009244 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009245 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9246 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9247 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9248 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9249 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009250 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009251 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009252 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009253 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009254 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009255 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009256
9257 if (needSep) pw.println(" ");
9258 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009259 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009260 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009261 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009262 needSep = true;
9263 }
9264
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009265 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009266
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009267 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009268 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009269 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009270 if (mHeavyWeightProcess != null) {
9271 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9272 }
9273
9274 return true;
9275 }
9276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009277 /**
9278 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009279 * - no provider specified: dump all the providers
9280 * - a flattened component name that matched an existing provider was specified as the
9281 * first arg: dump that one provider
9282 * - the first arg isn't the flattened component name of an existing provider:
9283 * dump all providers whose component contains the first arg as a substring
9284 */
9285 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9286 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009287 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009288 }
9289
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009290 static class ItemMatcher {
9291 ArrayList<ComponentName> components;
9292 ArrayList<String> strings;
9293 ArrayList<Integer> objects;
9294 boolean all;
9295
9296 ItemMatcher() {
9297 all = true;
9298 }
9299
9300 void build(String name) {
9301 ComponentName componentName = ComponentName.unflattenFromString(name);
9302 if (componentName != null) {
9303 if (components == null) {
9304 components = new ArrayList<ComponentName>();
9305 }
9306 components.add(componentName);
9307 all = false;
9308 } else {
9309 int objectId = 0;
9310 // Not a '/' separated full component name; maybe an object ID?
9311 try {
9312 objectId = Integer.parseInt(name, 16);
9313 if (objects == null) {
9314 objects = new ArrayList<Integer>();
9315 }
9316 objects.add(objectId);
9317 all = false;
9318 } catch (RuntimeException e) {
9319 // Not an integer; just do string match.
9320 if (strings == null) {
9321 strings = new ArrayList<String>();
9322 }
9323 strings.add(name);
9324 all = false;
9325 }
9326 }
9327 }
9328
9329 int build(String[] args, int opti) {
9330 for (; opti<args.length; opti++) {
9331 String name = args[opti];
9332 if ("--".equals(name)) {
9333 return opti+1;
9334 }
9335 build(name);
9336 }
9337 return opti;
9338 }
9339
9340 boolean match(Object object, ComponentName comp) {
9341 if (all) {
9342 return true;
9343 }
9344 if (components != null) {
9345 for (int i=0; i<components.size(); i++) {
9346 if (components.get(i).equals(comp)) {
9347 return true;
9348 }
9349 }
9350 }
9351 if (objects != null) {
9352 for (int i=0; i<objects.size(); i++) {
9353 if (System.identityHashCode(object) == objects.get(i)) {
9354 return true;
9355 }
9356 }
9357 }
9358 if (strings != null) {
9359 String flat = comp.flattenToString();
9360 for (int i=0; i<strings.size(); i++) {
9361 if (flat.contains(strings.get(i))) {
9362 return true;
9363 }
9364 }
9365 }
9366 return false;
9367 }
9368 }
9369
Dianne Hackborn625ac272010-09-17 18:29:22 -07009370 /**
9371 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009372 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009373 * - the cmd arg isn't the flattened component name of an existing activity:
9374 * dump all activity whose component contains the cmd as a substring
9375 * - A hex number of the ActivityRecord object instance.
9376 */
9377 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9378 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009379 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009380
9381 if ("all".equals(name)) {
9382 synchronized (this) {
9383 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009384 activities.add(r1);
9385 }
9386 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009387 } else if ("top".equals(name)) {
9388 synchronized (this) {
9389 final int N = mMainStack.mHistory.size();
9390 if (N > 0) {
9391 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9392 }
9393 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009394 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009395 ItemMatcher matcher = new ItemMatcher();
9396 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009397
9398 synchronized (this) {
9399 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009400 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009401 activities.add(r1);
9402 }
9403 }
9404 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009405 }
9406
9407 if (activities.size() <= 0) {
9408 return false;
9409 }
9410
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009411 String[] newArgs = new String[args.length - opti];
9412 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9413
Dianne Hackborn30d71892010-12-11 10:37:55 -08009414 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009415 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009416 for (int i=activities.size()-1; i>=0; i--) {
9417 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009418 if (needSep) {
9419 pw.println();
9420 }
9421 needSep = true;
9422 synchronized (this) {
9423 if (lastTask != r.task) {
9424 lastTask = r.task;
9425 pw.print("TASK "); pw.print(lastTask.affinity);
9426 pw.print(" id="); pw.println(lastTask.taskId);
9427 if (dumpAll) {
9428 lastTask.dump(pw, " ");
9429 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009430 }
9431 }
9432 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009433 }
9434 return true;
9435 }
9436
9437 /**
9438 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9439 * there is a thread associated with the activity.
9440 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009441 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009442 final ActivityRecord r, String[] args, boolean dumpAll) {
9443 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009444 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009445 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9446 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9447 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009448 if (r.app != null) pw.println(r.app.pid);
9449 else pw.println("(not running)");
9450 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009451 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009452 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009453 }
9454 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009455 // flush anything that is already in the PrintWriter since the thread is going
9456 // to write to the file descriptor directly
9457 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009458 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009459 TransferPipe tp = new TransferPipe();
9460 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009461 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9462 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009463 tp.go(fd);
9464 } finally {
9465 tp.kill();
9466 }
9467 } catch (IOException e) {
9468 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009469 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009470 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009471 }
9472 }
9473 }
9474
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009475 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009476 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009477 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009478 boolean onlyHistory = false;
9479
9480 if ("history".equals(dumpPackage)) {
9481 onlyHistory = true;
9482 dumpPackage = null;
9483 }
9484
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009485 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009486 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009487 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009488 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009489 Iterator it = mRegisteredReceivers.values().iterator();
9490 while (it.hasNext()) {
9491 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009492 if (dumpPackage != null && (r.app == null ||
9493 !dumpPackage.equals(r.app.info.packageName))) {
9494 continue;
9495 }
9496 if (!printed) {
9497 pw.println(" Registered Receivers:");
9498 needSep = true;
9499 printed = true;
9500 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009501 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009502 r.dump(pw, " ");
9503 }
9504 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009505
9506 if (mReceiverResolver.dump(pw, needSep ?
9507 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9508 " ", dumpPackage, false)) {
9509 needSep = true;
9510 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009511 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009512
9513 for (BroadcastQueue q : mBroadcastQueues) {
9514 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009516
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009517 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009518
Dianne Hackborn786b4402012-08-27 15:14:02 -07009519 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009520 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9521 if (needSep) {
9522 pw.println();
9523 }
9524 needSep = true;
9525 pw.print(" Sticky broadcasts for user ");
9526 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9527 StringBuilder sb = new StringBuilder(128);
9528 for (Map.Entry<String, ArrayList<Intent>> ent
9529 : mStickyBroadcasts.valueAt(user).entrySet()) {
9530 pw.print(" * Sticky action "); pw.print(ent.getKey());
9531 if (dumpAll) {
9532 pw.println(":");
9533 ArrayList<Intent> intents = ent.getValue();
9534 final int N = intents.size();
9535 for (int i=0; i<N; i++) {
9536 sb.setLength(0);
9537 sb.append(" Intent: ");
9538 intents.get(i).toShortString(sb, false, true, false, false);
9539 pw.println(sb.toString());
9540 Bundle bundle = intents.get(i).getExtras();
9541 if (bundle != null) {
9542 pw.print(" ");
9543 pw.println(bundle.toString());
9544 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009545 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009546 } else {
9547 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009548 }
9549 }
9550 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009551 }
9552
Dianne Hackborn786b4402012-08-27 15:14:02 -07009553 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009554 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009555 for (BroadcastQueue queue : mBroadcastQueues) {
9556 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9557 + queue.mBroadcastsScheduled);
9558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009559 pw.println(" mHandler:");
9560 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009561 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009562 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009563
9564 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009565 }
9566
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009567 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009568 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009569 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009570
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009571 ItemMatcher matcher = new ItemMatcher();
9572 matcher.build(args, opti);
9573
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009574 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009575
9576 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009577
9578 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009579 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009580 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009581 ContentProviderRecord r = mLaunchingProviders.get(i);
9582 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9583 continue;
9584 }
9585 if (!printed) {
9586 if (needSep) pw.println(" ");
9587 needSep = true;
9588 pw.println(" Launching content providers:");
9589 printed = true;
9590 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009591 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009592 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009593 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009594 }
9595
9596 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009597 if (needSep) pw.println();
9598 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009599 pw.println("Granted Uri Permissions:");
9600 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9601 int uid = mGrantedUriPermissions.keyAt(i);
9602 HashMap<Uri, UriPermission> perms
9603 = mGrantedUriPermissions.valueAt(i);
9604 pw.print(" * UID "); pw.print(uid);
9605 pw.println(" holds:");
9606 for (UriPermission perm : perms.values()) {
9607 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009608 if (dumpAll) {
9609 perm.dump(pw, " ");
9610 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009611 }
9612 }
9613 needSep = true;
9614 }
9615
9616 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009617 }
9618
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009619 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009620 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009621 boolean needSep = false;
9622
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009623 if (mIntentSenderRecords.size() > 0) {
9624 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009625 Iterator<WeakReference<PendingIntentRecord>> it
9626 = mIntentSenderRecords.values().iterator();
9627 while (it.hasNext()) {
9628 WeakReference<PendingIntentRecord> ref = it.next();
9629 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009630 if (dumpPackage != null && (rec == null
9631 || !dumpPackage.equals(rec.key.packageName))) {
9632 continue;
9633 }
9634 if (!printed) {
9635 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9636 printed = true;
9637 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009638 needSep = true;
9639 if (rec != null) {
9640 pw.print(" * "); pw.println(rec);
9641 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009642 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009643 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009644 } else {
9645 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009646 }
9647 }
9648 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009649
9650 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009651 }
9652
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009653 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009654 String prefix, String label, boolean complete, boolean brief, boolean client,
9655 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009656 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009657 boolean needNL = false;
9658 final String innerPrefix = prefix + " ";
9659 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009660 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009661 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009662 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9663 continue;
9664 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009665 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009666 if (needNL) {
9667 pw.println(" ");
9668 needNL = false;
9669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009670 if (lastTask != r.task) {
9671 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009672 pw.print(prefix);
9673 pw.print(full ? "* " : " ");
9674 pw.println(lastTask);
9675 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009676 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009677 } else if (complete) {
9678 // Complete + brief == give a summary. Isn't that obvious?!?
9679 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009680 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009681 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009682 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009684 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009685 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9686 pw.print(" #"); pw.print(i); pw.print(": ");
9687 pw.println(r);
9688 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009689 r.dump(pw, innerPrefix);
9690 } else if (complete) {
9691 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009692 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009693 if (r.app != null) {
9694 pw.print(innerPrefix); pw.println(r.app);
9695 }
9696 }
9697 if (client && r.app != null && r.app.thread != null) {
9698 // flush anything that is already in the PrintWriter since the thread is going
9699 // to write to the file descriptor directly
9700 pw.flush();
9701 try {
9702 TransferPipe tp = new TransferPipe();
9703 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009704 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9705 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009706 // Short timeout, since blocking here can
9707 // deadlock with the application.
9708 tp.go(fd, 2000);
9709 } finally {
9710 tp.kill();
9711 }
9712 } catch (IOException e) {
9713 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9714 } catch (RemoteException e) {
9715 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9716 }
9717 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009719 }
9720 }
9721
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009722 private static String buildOomTag(String prefix, String space, int val, int base) {
9723 if (val == base) {
9724 if (space == null) return prefix;
9725 return prefix + " ";
9726 }
9727 return prefix + "+" + Integer.toString(val-base);
9728 }
9729
9730 private static final int dumpProcessList(PrintWriter pw,
9731 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009732 String prefix, String normalLabel, String persistentLabel,
9733 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009734 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009735 final int N = list.size()-1;
9736 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009737 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009738 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9739 continue;
9740 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009741 pw.println(String.format("%s%s #%2d: %s",
9742 prefix, (r.persistent ? persistentLabel : normalLabel),
9743 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009744 if (r.persistent) {
9745 numPers++;
9746 }
9747 }
9748 return numPers;
9749 }
9750
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009751 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009752 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009753 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009754 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009755
Dianne Hackborn905577f2011-09-07 18:31:28 -07009756 ArrayList<Pair<ProcessRecord, Integer>> list
9757 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9758 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009759 ProcessRecord r = origList.get(i);
9760 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9761 continue;
9762 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009763 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9764 }
9765
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009766 if (list.size() <= 0) {
9767 return false;
9768 }
9769
Dianne Hackborn905577f2011-09-07 18:31:28 -07009770 Comparator<Pair<ProcessRecord, Integer>> comparator
9771 = new Comparator<Pair<ProcessRecord, Integer>>() {
9772 @Override
9773 public int compare(Pair<ProcessRecord, Integer> object1,
9774 Pair<ProcessRecord, Integer> object2) {
9775 if (object1.first.setAdj != object2.first.setAdj) {
9776 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9777 }
9778 if (object1.second.intValue() != object2.second.intValue()) {
9779 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9780 }
9781 return 0;
9782 }
9783 };
9784
9785 Collections.sort(list, comparator);
9786
Dianne Hackborn287952c2010-09-22 22:34:31 -07009787 final long curRealtime = SystemClock.elapsedRealtime();
9788 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9789 final long curUptime = SystemClock.uptimeMillis();
9790 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9791
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009792 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009793 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009794 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009795 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009796 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009797 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9798 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009799 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9800 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009801 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9802 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009803 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9804 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009805 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009806 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009807 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9808 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9809 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9810 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9811 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9812 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9813 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9814 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009815 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9816 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009817 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9818 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009819 } else {
9820 oomAdj = Integer.toString(r.setAdj);
9821 }
9822 String schedGroup;
9823 switch (r.setSchedGroup) {
9824 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9825 schedGroup = "B";
9826 break;
9827 case Process.THREAD_GROUP_DEFAULT:
9828 schedGroup = "F";
9829 break;
9830 default:
9831 schedGroup = Integer.toString(r.setSchedGroup);
9832 break;
9833 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009834 String foreground;
9835 if (r.foregroundActivities) {
9836 foreground = "A";
9837 } else if (r.foregroundServices) {
9838 foreground = "S";
9839 } else {
9840 foreground = " ";
9841 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009842 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009843 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009844 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9845 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009846 if (r.adjSource != null || r.adjTarget != null) {
9847 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009848 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009849 if (r.adjTarget instanceof ComponentName) {
9850 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9851 } else if (r.adjTarget != null) {
9852 pw.print(r.adjTarget.toString());
9853 } else {
9854 pw.print("{null}");
9855 }
9856 pw.print("<=");
9857 if (r.adjSource instanceof ProcessRecord) {
9858 pw.print("Proc{");
9859 pw.print(((ProcessRecord)r.adjSource).toShortString());
9860 pw.println("}");
9861 } else if (r.adjSource != null) {
9862 pw.println(r.adjSource.toString());
9863 } else {
9864 pw.println("{null}");
9865 }
9866 }
9867 if (inclDetails) {
9868 pw.print(prefix);
9869 pw.print(" ");
9870 pw.print("oom: max="); pw.print(r.maxAdj);
9871 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009872 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009873 pw.print(" curRaw="); pw.print(r.curRawAdj);
9874 pw.print(" setRaw="); pw.print(r.setRawAdj);
9875 pw.print(" cur="); pw.print(r.curAdj);
9876 pw.print(" set="); pw.println(r.setAdj);
9877 pw.print(prefix);
9878 pw.print(" ");
9879 pw.print("keeping="); pw.print(r.keeping);
9880 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009881 pw.print(" empty="); pw.print(r.empty);
9882 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009883
9884 if (!r.keeping) {
9885 if (r.lastWakeTime != 0) {
9886 long wtime;
9887 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9888 synchronized (stats) {
9889 wtime = stats.getProcessWakeTime(r.info.uid,
9890 r.pid, curRealtime);
9891 }
9892 long timeUsed = wtime - r.lastWakeTime;
9893 pw.print(prefix);
9894 pw.print(" ");
9895 pw.print("keep awake over ");
9896 TimeUtils.formatDuration(realtimeSince, pw);
9897 pw.print(" used ");
9898 TimeUtils.formatDuration(timeUsed, pw);
9899 pw.print(" (");
9900 pw.print((timeUsed*100)/realtimeSince);
9901 pw.println("%)");
9902 }
9903 if (r.lastCpuTime != 0) {
9904 long timeUsed = r.curCpuTime - r.lastCpuTime;
9905 pw.print(prefix);
9906 pw.print(" ");
9907 pw.print("run cpu over ");
9908 TimeUtils.formatDuration(uptimeSince, pw);
9909 pw.print(" used ");
9910 TimeUtils.formatDuration(timeUsed, pw);
9911 pw.print(" (");
9912 pw.print((timeUsed*100)/uptimeSince);
9913 pw.println("%)");
9914 }
9915 }
9916 }
9917 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009918 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009919 }
9920
Dianne Hackbornb437e092011-08-05 17:50:29 -07009921 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009922 ArrayList<ProcessRecord> procs;
9923 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009924 if (args != null && args.length > start
9925 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009926 procs = new ArrayList<ProcessRecord>();
9927 int pid = -1;
9928 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009929 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009930 } catch (NumberFormatException e) {
9931
9932 }
9933 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9934 ProcessRecord proc = mLruProcesses.get(i);
9935 if (proc.pid == pid) {
9936 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009937 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009938 procs.add(proc);
9939 }
9940 }
9941 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009942 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009943 return null;
9944 }
9945 } else {
9946 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9947 }
9948 }
9949 return procs;
9950 }
9951
9952 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9953 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009954 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009955 if (procs == null) {
9956 return;
9957 }
9958
9959 long uptime = SystemClock.uptimeMillis();
9960 long realtime = SystemClock.elapsedRealtime();
9961 pw.println("Applications Graphics Acceleration Info:");
9962 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9963
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009964 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9965 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009966 if (r.thread != null) {
9967 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9968 pw.flush();
9969 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009970 TransferPipe tp = new TransferPipe();
9971 try {
9972 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9973 tp.go(fd);
9974 } finally {
9975 tp.kill();
9976 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009977 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009978 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009979 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009980 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009981 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009982 pw.flush();
9983 }
9984 }
9985 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009986 }
9987
Jeff Brown6754ba22011-12-14 20:20:01 -08009988 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9989 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9990 if (procs == null) {
9991 return;
9992 }
9993
9994 pw.println("Applications Database Info:");
9995
9996 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9997 ProcessRecord r = procs.get(i);
9998 if (r.thread != null) {
9999 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10000 pw.flush();
10001 try {
10002 TransferPipe tp = new TransferPipe();
10003 try {
10004 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10005 tp.go(fd);
10006 } finally {
10007 tp.kill();
10008 }
10009 } catch (IOException e) {
10010 pw.println("Failure while dumping the app: " + r);
10011 pw.flush();
10012 } catch (RemoteException e) {
10013 pw.println("Got a RemoteException while dumping the app " + r);
10014 pw.flush();
10015 }
10016 }
10017 }
10018 }
10019
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010020 final static class MemItem {
10021 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010022 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010023 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010024 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010025 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010026
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010027 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010028 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010029 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010030 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010031 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010032 }
10033 }
10034
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010035 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010036 boolean sort) {
10037 if (sort) {
10038 Collections.sort(items, new Comparator<MemItem>() {
10039 @Override
10040 public int compare(MemItem lhs, MemItem rhs) {
10041 if (lhs.pss < rhs.pss) {
10042 return 1;
10043 } else if (lhs.pss > rhs.pss) {
10044 return -1;
10045 }
10046 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010047 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010048 });
10049 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010050
10051 for (int i=0; i<items.size(); i++) {
10052 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010053 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010054 if (mi.subitems != null) {
10055 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10056 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010057 }
10058 }
10059
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010060 // These are in KB.
10061 static final long[] DUMP_MEM_BUCKETS = new long[] {
10062 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10063 120*1024, 160*1024, 200*1024,
10064 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10065 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10066 };
10067
Dianne Hackborn672342c2011-11-29 11:29:02 -080010068 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10069 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010070 int start = label.lastIndexOf('.');
10071 if (start >= 0) start++;
10072 else start = 0;
10073 int end = label.length();
10074 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10075 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10076 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10077 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010078 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010079 out.append(label, start, end);
10080 return;
10081 }
10082 }
10083 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010084 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010085 out.append(label, start, end);
10086 }
10087
10088 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10089 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10090 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10091 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10092 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10093 };
10094 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10095 "System", "Persistent", "Foreground",
10096 "Visible", "Perceptible", "Heavy Weight",
10097 "Backup", "A Services", "Home", "Previous",
10098 "B Services", "Background"
10099 };
10100
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010101 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010102 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010103 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010104 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010105 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010106
10107 int opti = 0;
10108 while (opti < args.length) {
10109 String opt = args[opti];
10110 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10111 break;
10112 }
10113 opti++;
10114 if ("-a".equals(opt)) {
10115 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010116 } else if ("--oom".equals(opt)) {
10117 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010118 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010119 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010120 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010121 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010122 pw.println("If [process] is specified it can be the name or ");
10123 pw.println("pid of a specific process to dump.");
10124 return;
10125 } else {
10126 pw.println("Unknown argument: " + opt + "; use -h for help");
10127 }
10128 }
10129
10130 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010131 if (procs == null) {
10132 return;
10133 }
10134
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010135 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010136 long uptime = SystemClock.uptimeMillis();
10137 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010138
10139 if (procs.size() == 1 || isCheckinRequest) {
10140 dumpAll = true;
10141 }
10142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010143 if (isCheckinRequest) {
10144 // short checkin version
10145 pw.println(uptime + "," + realtime);
10146 pw.flush();
10147 } else {
10148 pw.println("Applications Memory Usage (kB):");
10149 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10150 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010151
Dianne Hackbornb437e092011-08-05 17:50:29 -070010152 String[] innerArgs = new String[args.length-opti];
10153 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10154
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010155 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10156 long nativePss=0, dalvikPss=0, otherPss=0;
10157 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10158
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010159 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10160 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10161 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010162
10163 long totalPss = 0;
10164
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010165 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10166 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010167 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010168 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010169 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10170 pw.flush();
10171 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010172 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010173 if (dumpAll) {
10174 try {
10175 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10176 } catch (RemoteException e) {
10177 if (!isCheckinRequest) {
10178 pw.println("Got RemoteException!");
10179 pw.flush();
10180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010181 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010182 } else {
10183 mi = new Debug.MemoryInfo();
10184 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010185 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010186
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010187 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010188 long myTotalPss = mi.getTotalPss();
10189 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010190 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010191 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010192 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010193
10194 nativePss += mi.nativePss;
10195 dalvikPss += mi.dalvikPss;
10196 otherPss += mi.otherPss;
10197 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10198 long mem = mi.getOtherPss(j);
10199 miscPss[j] += mem;
10200 otherPss -= mem;
10201 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010202
10203 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010204 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10205 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010206 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010207 if (oomProcs[oomIndex] == null) {
10208 oomProcs[oomIndex] = new ArrayList<MemItem>();
10209 }
10210 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010211 break;
10212 }
10213 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010215 }
10216 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010217
10218 if (!isCheckinRequest && procs.size() > 1) {
10219 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10220
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010221 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10222 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10223 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010224 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010225 String label = Debug.MemoryInfo.getOtherLabel(j);
10226 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010227 }
10228
Dianne Hackbornb437e092011-08-05 17:50:29 -070010229 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10230 for (int j=0; j<oomPss.length; j++) {
10231 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010232 String label = DUMP_MEM_OOM_LABEL[j];
10233 MemItem item = new MemItem(label, label, oomPss[j],
10234 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010235 item.subitems = oomProcs[j];
10236 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010237 }
10238 }
10239
Dianne Hackborn672342c2011-11-29 11:29:02 -080010240 if (outTag != null || outStack != null) {
10241 if (outTag != null) {
10242 appendMemBucket(outTag, totalPss, "total", false);
10243 }
10244 if (outStack != null) {
10245 appendMemBucket(outStack, totalPss, "total", true);
10246 }
10247 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010248 for (int i=0; i<oomMems.size(); i++) {
10249 MemItem miCat = oomMems.get(i);
10250 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10251 continue;
10252 }
10253 if (miCat.id < ProcessList.SERVICE_ADJ
10254 || miCat.id == ProcessList.HOME_APP_ADJ
10255 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010256 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10257 outTag.append(" / ");
10258 }
10259 if (outStack != null) {
10260 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10261 if (firstLine) {
10262 outStack.append(":");
10263 firstLine = false;
10264 }
10265 outStack.append("\n\t at ");
10266 } else {
10267 outStack.append("$");
10268 }
10269 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010270 for (int j=0; j<miCat.subitems.size(); j++) {
10271 MemItem mi = miCat.subitems.get(j);
10272 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010273 if (outTag != null) {
10274 outTag.append(" ");
10275 }
10276 if (outStack != null) {
10277 outStack.append("$");
10278 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010279 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010280 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10281 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10282 }
10283 if (outStack != null) {
10284 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10285 }
10286 }
10287 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10288 outStack.append("(");
10289 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10290 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10291 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10292 outStack.append(":");
10293 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10294 }
10295 }
10296 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010297 }
10298 }
10299 }
10300 }
10301
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010302 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010303 pw.println();
10304 pw.println("Total PSS by process:");
10305 dumpMemItems(pw, " ", procMems, true);
10306 pw.println();
10307 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010308 pw.println("Total PSS by OOM adjustment:");
10309 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010310 if (!oomOnly) {
10311 PrintWriter out = categoryPw != null ? categoryPw : pw;
10312 out.println();
10313 out.println("Total PSS by category:");
10314 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010315 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010316 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010317 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010318 final int[] SINGLE_LONG_FORMAT = new int[] {
10319 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10320 };
10321 long[] longOut = new long[1];
10322 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10323 SINGLE_LONG_FORMAT, null, longOut, null);
10324 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10325 longOut[0] = 0;
10326 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10327 SINGLE_LONG_FORMAT, null, longOut, null);
10328 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10329 longOut[0] = 0;
10330 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10331 SINGLE_LONG_FORMAT, null, longOut, null);
10332 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10333 longOut[0] = 0;
10334 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10335 SINGLE_LONG_FORMAT, null, longOut, null);
10336 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10337 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10338 pw.print(shared); pw.println(" kB");
10339 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10340 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010342 }
10343
10344 /**
10345 * Searches array of arguments for the specified string
10346 * @param args array of argument strings
10347 * @param value value to search for
10348 * @return true if the value is contained in the array
10349 */
10350 private static boolean scanArgs(String[] args, String value) {
10351 if (args != null) {
10352 for (String arg : args) {
10353 if (value.equals(arg)) {
10354 return true;
10355 }
10356 }
10357 }
10358 return false;
10359 }
10360
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010361 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10362 ContentProviderRecord cpr, boolean always) {
10363 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10364
10365 if (!inLaunching || always) {
10366 synchronized (cpr) {
10367 cpr.launchingApp = null;
10368 cpr.notifyAll();
10369 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010370 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010371 String names[] = cpr.info.authority.split(";");
10372 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010373 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010374 }
10375 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010376
10377 for (int i=0; i<cpr.connections.size(); i++) {
10378 ContentProviderConnection conn = cpr.connections.get(i);
10379 if (conn.waiting) {
10380 // If this connection is waiting for the provider, then we don't
10381 // need to mess with its process unless we are always removing
10382 // or for some reason the provider is not currently launching.
10383 if (inLaunching && !always) {
10384 continue;
10385 }
10386 }
10387 ProcessRecord capp = conn.client;
10388 conn.dead = true;
10389 if (conn.stableCount > 0) {
10390 if (!capp.persistent && capp.thread != null
10391 && capp.pid != 0
10392 && capp.pid != MY_PID) {
10393 Slog.i(TAG, "Kill " + capp.processName
10394 + " (pid " + capp.pid + "): provider " + cpr.info.name
10395 + " in dying process " + (proc != null ? proc.processName : "??"));
10396 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10397 capp.processName, capp.setAdj, "dying provider "
10398 + cpr.name.toShortString());
10399 Process.killProcessQuiet(capp.pid);
10400 }
10401 } else if (capp.thread != null && conn.provider.provider != null) {
10402 try {
10403 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10404 } catch (RemoteException e) {
10405 }
10406 // In the protocol here, we don't expect the client to correctly
10407 // clean up this connection, we'll just remove it.
10408 cpr.connections.remove(i);
10409 conn.client.conProviders.remove(conn);
10410 }
10411 }
10412
10413 if (inLaunching && always) {
10414 mLaunchingProviders.remove(cpr);
10415 }
10416 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010417 }
10418
10419 /**
10420 * Main code for cleaning up a process when it has gone away. This is
10421 * called both as a result of the process dying, or directly when stopping
10422 * a process when running in single process mode.
10423 */
10424 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010425 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010426 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010427 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010428 }
10429
Dianne Hackborn36124872009-10-08 16:22:03 -070010430 mProcessesToGc.remove(app);
10431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010432 // Dismiss any open dialogs.
10433 if (app.crashDialog != null) {
10434 app.crashDialog.dismiss();
10435 app.crashDialog = null;
10436 }
10437 if (app.anrDialog != null) {
10438 app.anrDialog.dismiss();
10439 app.anrDialog = null;
10440 }
10441 if (app.waitDialog != null) {
10442 app.waitDialog.dismiss();
10443 app.waitDialog = null;
10444 }
10445
10446 app.crashing = false;
10447 app.notResponding = false;
10448
10449 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010450 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010451 app.thread = null;
10452 app.forcingToForeground = null;
10453 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010454 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010455 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010456 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010457
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010458 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010459
10460 boolean restart = false;
10461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010462 // Remove published content providers.
10463 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010464 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010465 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010466 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010467
10468 final boolean always = app.bad || !allowRestart;
10469 if (removeDyingProviderLocked(app, cpr, always) || always) {
10470 // We left the provider in the launching list, need to
10471 // restart it.
10472 restart = true;
10473 }
10474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010475 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010476 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010477 }
10478 app.pubProviders.clear();
10479 }
10480
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010481 // Take care of any launching providers waiting for this process.
10482 if (checkAppInLaunchingProvidersLocked(app, false)) {
10483 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010484 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010486 // Unregister from connected content providers.
10487 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010488 for (int i=0; i<app.conProviders.size(); i++) {
10489 ContentProviderConnection conn = app.conProviders.get(i);
10490 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010491 }
10492 app.conProviders.clear();
10493 }
10494
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010495 // At this point there may be remaining entries in mLaunchingProviders
10496 // where we were the only one waiting, so they are no longer of use.
10497 // Look for these and clean up if found.
10498 // XXX Commented out for now. Trying to figure out a way to reproduce
10499 // the actual situation to identify what is actually going on.
10500 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010501 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010502 ContentProviderRecord cpr = (ContentProviderRecord)
10503 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010504 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010505 synchronized (cpr) {
10506 cpr.launchingApp = null;
10507 cpr.notifyAll();
10508 }
10509 }
10510 }
10511 }
10512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010513 skipCurrentReceiverLocked(app);
10514
10515 // Unregister any receivers.
10516 if (app.receivers.size() > 0) {
10517 Iterator<ReceiverList> it = app.receivers.iterator();
10518 while (it.hasNext()) {
10519 removeReceiverLocked(it.next());
10520 }
10521 app.receivers.clear();
10522 }
10523
Christopher Tate181fafa2009-05-14 11:12:14 -070010524 // If the app is undergoing backup, tell the backup manager about it
10525 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010526 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010527 try {
10528 IBackupManager bm = IBackupManager.Stub.asInterface(
10529 ServiceManager.getService(Context.BACKUP_SERVICE));
10530 bm.agentDisconnected(app.info.packageName);
10531 } catch (RemoteException e) {
10532 // can't happen; backup manager is local
10533 }
10534 }
10535
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010536 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10537 ProcessChangeItem item = mPendingProcessChanges.get(i);
10538 if (item.pid == app.pid) {
10539 mPendingProcessChanges.remove(i);
10540 mAvailProcessChanges.add(item);
10541 }
10542 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010543 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010545 // If the caller is restarting this app, then leave it in its
10546 // current lists and let the caller take care of it.
10547 if (restarting) {
10548 return;
10549 }
10550
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010551 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010552 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010553 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010554 mProcessNames.remove(app.processName, app.uid);
10555 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010556 if (mHeavyWeightProcess == app) {
Dianne Hackborn41203752012-08-31 14:05:51 -070010557 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG,
10558 mHeavyWeightProcess.userId, 0));
Dianne Hackborn860755f2010-06-03 18:47:52 -070010559 mHeavyWeightProcess = null;
Dianne Hackborn860755f2010-06-03 18:47:52 -070010560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010561 } else if (!app.removed) {
10562 // This app is persistent, so we need to keep its record around.
10563 // If it is not already on the pending app list, add it there
10564 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010565 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10566 mPersistentStartingProcesses.add(app);
10567 restart = true;
10568 }
10569 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010570 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10571 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010572 mProcessesOnHold.remove(app);
10573
The Android Open Source Project4df24232009-03-05 14:34:35 -080010574 if (app == mHomeProcess) {
10575 mHomeProcess = null;
10576 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010577 if (app == mPreviousProcess) {
10578 mPreviousProcess = null;
10579 }
10580
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010581 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010582 // We have components that still need to be running in the
10583 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010584 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010585 startProcessLocked(app, "restart", app.processName);
10586 } else if (app.pid > 0 && app.pid != MY_PID) {
10587 // Goodbye!
10588 synchronized (mPidsSelfLocked) {
10589 mPidsSelfLocked.remove(app.pid);
10590 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10591 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010592 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010593 }
10594 }
10595
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010596 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10597 // Look through the content providers we are waiting to have launched,
10598 // and if any run in this process then either schedule a restart of
10599 // the process or kill the client waiting for it if this process has
10600 // gone bad.
10601 int NL = mLaunchingProviders.size();
10602 boolean restart = false;
10603 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010604 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010605 if (cpr.launchingApp == app) {
10606 if (!alwaysBad && !app.bad) {
10607 restart = true;
10608 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010609 removeDyingProviderLocked(app, cpr, true);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010610 NL = mLaunchingProviders.size();
10611 }
10612 }
10613 }
10614 return restart;
10615 }
10616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010617 // =========================================================
10618 // SERVICES
10619 // =========================================================
10620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010621 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10622 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010623 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010624 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010625 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010626 }
10627 }
10628
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010629 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010630 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010631 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010632 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010633 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010634 }
10635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010636 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010637 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010638 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010639 // Refuse possible leaked file descriptors
10640 if (service != null && service.hasFileDescriptors() == true) {
10641 throw new IllegalArgumentException("File descriptors passed in Intent");
10642 }
10643
Amith Yamasani742a6712011-05-04 14:49:28 -070010644 if (DEBUG_SERVICE)
10645 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010646 synchronized(this) {
10647 final int callingPid = Binder.getCallingPid();
10648 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010649 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010650 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010651 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010652 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010653 Binder.restoreCallingIdentity(origId);
10654 return res;
10655 }
10656 }
10657
10658 ComponentName startServiceInPackage(int uid,
Dianne Hackborn41203752012-08-31 14:05:51 -070010659 Intent service, String resolvedType, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010660 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010661 if (DEBUG_SERVICE)
10662 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010663 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010664 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn41203752012-08-31 14:05:51 -070010665 resolvedType, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010666 Binder.restoreCallingIdentity(origId);
10667 return res;
10668 }
10669 }
10670
10671 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010672 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010673 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010674 // Refuse possible leaked file descriptors
10675 if (service != null && service.hasFileDescriptors() == true) {
10676 throw new IllegalArgumentException("File descriptors passed in Intent");
10677 }
10678
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010679 checkValidCaller(Binder.getCallingUid(), userId);
10680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010681 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010682 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010684 }
10685
10686 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010687 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010688 // Refuse possible leaked file descriptors
10689 if (service != null && service.hasFileDescriptors() == true) {
10690 throw new IllegalArgumentException("File descriptors passed in Intent");
10691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010692 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010693 return mServices.peekServiceLocked(service, resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010694 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010695 }
10696
10697 public boolean stopServiceToken(ComponentName className, IBinder token,
10698 int startId) {
10699 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010700 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010702 }
10703
10704 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010705 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010706 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010707 mServices.setServiceForegroundLocked(className, token, id, notification,
10708 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010709 }
10710 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010711
Dianne Hackborn41203752012-08-31 14:05:51 -070010712 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
10713 boolean requireFull, String name, String callerPackage) {
10714 synchronized(this) {
10715 return handleIncomingUserLocked(callingPid, callingUid, userId, allowAll,
10716 requireFull, name, callerPackage);
10717 }
10718 }
10719
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010720 int handleIncomingUserLocked(int callingPid, int callingUid, int userId, boolean allowAll,
10721 boolean requireFull, String name, String callerPackage) {
10722 final int callingUserId = UserHandle.getUserId(callingUid);
10723 if (callingUserId != userId) {
10724 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10725 if ((requireFull || checkComponentPermission(
10726 android.Manifest.permission.INTERACT_ACROSS_USERS,
10727 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10728 && checkComponentPermission(
10729 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10730 callingPid, callingUid, -1, true)
10731 != PackageManager.PERMISSION_GRANTED) {
10732 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10733 // In this case, they would like to just execute as their
10734 // owner user instead of failing.
10735 userId = callingUserId;
10736 } else {
Dianne Hackborn41203752012-08-31 14:05:51 -070010737 StringBuilder builder = new StringBuilder(128);
10738 builder.append("Permission Denial: ");
10739 builder.append(name);
10740 if (callerPackage != null) {
10741 builder.append(" from ");
10742 builder.append(callerPackage);
10743 }
10744 builder.append(" asks to run as user ");
10745 builder.append(userId);
10746 builder.append(" but is calling from user ");
10747 builder.append(UserHandle.getUserId(callingUid));
10748 builder.append("; this requires ");
10749 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL);
10750 if (!requireFull) {
10751 builder.append("or");
10752 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS);
10753 }
10754 String msg = builder.toString();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010755 Slog.w(TAG, msg);
10756 throw new SecurityException(msg);
10757 }
10758 }
10759 }
10760 if (userId == UserHandle.USER_CURRENT
10761 || userId == UserHandle.USER_CURRENT_OR_SELF) {
10762 userId = mCurrentUserId;
10763 }
10764 if (!allowAll && userId < 0) {
10765 throw new IllegalArgumentException(
10766 "Call does not support special user #" + userId);
10767 }
10768 }
10769 return userId;
10770 }
10771
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010772 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10773 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010774 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010775 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010776 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10777 if (ActivityManager.checkUidPermission(
10778 android.Manifest.permission.INTERACT_ACROSS_USERS,
10779 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10780 ComponentName comp = new ComponentName(aInfo.packageName, className);
10781 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10782 + " requests FLAG_SINGLE_USER, but app does not hold "
10783 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10784 Slog.w(TAG, msg);
10785 throw new SecurityException(msg);
10786 }
10787 result = true;
10788 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010789 } else if (componentProcessName == aInfo.packageName) {
10790 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10791 } else if ("system".equals(componentProcessName)) {
10792 result = true;
10793 }
10794 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010795 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10796 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010797 }
10798 return result;
10799 }
10800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010801 public int bindService(IApplicationThread caller, IBinder token,
10802 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010803 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010804 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010805 // Refuse possible leaked file descriptors
10806 if (service != null && service.hasFileDescriptors() == true) {
10807 throw new IllegalArgumentException("File descriptors passed in Intent");
10808 }
10809
10810 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010811 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10812 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010813 }
10814 }
10815
10816 public boolean unbindService(IServiceConnection connection) {
10817 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010818 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010820 }
10821
10822 public void publishService(IBinder token, Intent intent, IBinder service) {
10823 // Refuse possible leaked file descriptors
10824 if (intent != null && intent.hasFileDescriptors() == true) {
10825 throw new IllegalArgumentException("File descriptors passed in Intent");
10826 }
10827
10828 synchronized(this) {
10829 if (!(token instanceof ServiceRecord)) {
10830 throw new IllegalArgumentException("Invalid service token");
10831 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010832 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010833 }
10834 }
10835
10836 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10837 // Refuse possible leaked file descriptors
10838 if (intent != null && intent.hasFileDescriptors() == true) {
10839 throw new IllegalArgumentException("File descriptors passed in Intent");
10840 }
10841
10842 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010843 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010844 }
10845 }
10846
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010847 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010848 synchronized(this) {
10849 if (!(token instanceof ServiceRecord)) {
10850 throw new IllegalArgumentException("Invalid service token");
10851 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010852 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010854 }
10855
10856 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010857 // BACKUP AND RESTORE
10858 // =========================================================
10859
10860 // Cause the target app to be launched if necessary and its backup agent
10861 // instantiated. The backup agent will invoke backupAgentCreated() on the
10862 // activity manager to announce its creation.
10863 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010864 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010865 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10866
10867 synchronized(this) {
10868 // !!! TODO: currently no check here that we're already bound
10869 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10870 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10871 synchronized (stats) {
10872 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10873 }
10874
Dianne Hackborne7f97212011-02-24 14:40:20 -080010875 // Backup agent is now in use, its package can't be stopped.
10876 try {
10877 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010878 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080010879 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010880 } catch (IllegalArgumentException e) {
10881 Slog.w(TAG, "Failed trying to unstop package "
10882 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010883 }
10884
Christopher Tate181fafa2009-05-14 11:12:14 -070010885 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070010886 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
10887 ? new ComponentName(app.packageName, app.backupAgentName)
10888 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070010889 // startProcessLocked() returns existing proc's record if it's already running
10890 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010891 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010892 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010893 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010894 return false;
10895 }
10896
10897 r.app = proc;
10898 mBackupTarget = r;
10899 mBackupAppName = app.packageName;
10900
Christopher Tate6fa95972009-06-05 18:43:55 -070010901 // Try not to kill the process during backup
10902 updateOomAdjLocked(proc);
10903
Christopher Tate181fafa2009-05-14 11:12:14 -070010904 // If the process is already attached, schedule the creation of the backup agent now.
10905 // If it is not yet live, this will be done when it attaches to the framework.
10906 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010907 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070010908 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010909 proc.thread.scheduleCreateBackupAgent(app,
10910 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010911 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070010912 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070010913 }
10914 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010915 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070010916 }
10917 // Invariants: at this point, the target app process exists and the application
10918 // is either already running or in the process of coming up. mBackupTarget and
10919 // mBackupAppName describe the app, so that when it binds back to the AM we
10920 // know that it's scheduled for a backup-agent operation.
10921 }
10922
10923 return true;
10924 }
10925
10926 // A backup agent has just come up
10927 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010928 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070010929 + " = " + agent);
10930
10931 synchronized(this) {
10932 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010933 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070010934 return;
10935 }
Dianne Hackborn06740692010-09-22 22:46:21 -070010936 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010937
Dianne Hackborn06740692010-09-22 22:46:21 -070010938 long oldIdent = Binder.clearCallingIdentity();
10939 try {
10940 IBackupManager bm = IBackupManager.Stub.asInterface(
10941 ServiceManager.getService(Context.BACKUP_SERVICE));
10942 bm.agentConnected(agentPackageName, agent);
10943 } catch (RemoteException e) {
10944 // can't happen; the backup manager service is local
10945 } catch (Exception e) {
10946 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
10947 e.printStackTrace();
10948 } finally {
10949 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070010950 }
10951 }
10952
10953 // done with this agent
10954 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010955 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070010956 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010957 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070010958 return;
10959 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010960
10961 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070010962 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010963 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070010964 return;
10965 }
10966
Christopher Tate181fafa2009-05-14 11:12:14 -070010967 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010968 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070010969 return;
10970 }
10971
Christopher Tate6fa95972009-06-05 18:43:55 -070010972 ProcessRecord proc = mBackupTarget.app;
10973 mBackupTarget = null;
10974 mBackupAppName = null;
10975
10976 // Not backing this app up any more; reset its OOM adjustment
10977 updateOomAdjLocked(proc);
10978
Christopher Tatec7b31e32009-06-10 15:49:30 -070010979 // If the app crashed during backup, 'thread' will be null here
10980 if (proc.thread != null) {
10981 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010982 proc.thread.scheduleDestroyBackupAgent(appInfo,
10983 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070010984 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010985 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070010986 e.printStackTrace();
10987 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010988 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010989 }
10990 }
10991 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010992 // BROADCASTS
10993 // =========================================================
10994
Josh Bartel7f208742010-02-25 11:01:44 -060010995 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010996 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010997 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010998 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
10999 if (stickies == null) {
11000 return cur;
11001 }
11002 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011003 if (list == null) {
11004 return cur;
11005 }
11006 int N = list.size();
11007 for (int i=0; i<N; i++) {
11008 Intent intent = list.get(i);
11009 if (filter.match(resolver, intent, true, TAG) >= 0) {
11010 if (cur == null) {
11011 cur = new ArrayList<Intent>();
11012 }
11013 cur.add(intent);
11014 }
11015 }
11016 return cur;
11017 }
11018
Christopher Tatef46723b2012-01-26 14:19:24 -080011019 boolean isPendingBroadcastProcessLocked(int pid) {
11020 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11021 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011023
Christopher Tatef46723b2012-01-26 14:19:24 -080011024 void skipPendingBroadcastLocked(int pid) {
11025 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11026 for (BroadcastQueue queue : mBroadcastQueues) {
11027 queue.skipPendingBroadcastLocked(pid);
11028 }
11029 }
11030
11031 // The app just attached; send any pending broadcasts that it should receive
11032 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11033 boolean didSomething = false;
11034 for (BroadcastQueue queue : mBroadcastQueues) {
11035 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011036 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011037 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011038 }
11039
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011040 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011041 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011042 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011043 int callingUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011044 synchronized(this) {
11045 ProcessRecord callerApp = null;
11046 if (caller != null) {
11047 callerApp = getRecordForAppLocked(caller);
11048 if (callerApp == null) {
11049 throw new SecurityException(
11050 "Unable to find app for caller " + caller
11051 + " (pid=" + Binder.getCallingPid()
11052 + ") when registering receiver " + receiver);
11053 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011054 if (callerApp.info.uid != Process.SYSTEM_UID &&
11055 !callerApp.pkgList.contains(callerPackage)) {
11056 throw new SecurityException("Given caller package " + callerPackage
11057 + " is not running in process " + callerApp);
11058 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011059 callingUid = callerApp.info.uid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011060 } else {
11061 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011062 callingUid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011063 }
11064
11065 List allSticky = null;
11066
11067 // Look for any matching sticky broadcasts...
11068 Iterator actions = filter.actionsIterator();
11069 if (actions != null) {
11070 while (actions.hasNext()) {
11071 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011072 allSticky = getStickiesLocked(action, filter, allSticky,
11073 UserHandle.USER_ALL);
11074 allSticky = getStickiesLocked(action, filter, allSticky,
11075 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011076 }
11077 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011078 allSticky = getStickiesLocked(null, filter, allSticky,
11079 UserHandle.USER_ALL);
11080 allSticky = getStickiesLocked(null, filter, allSticky,
11081 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011082 }
11083
11084 // The first sticky in the list is returned directly back to
11085 // the client.
11086 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11087
Joe Onorato8a9b2202010-02-26 18:56:32 -080011088 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011089 + ": " + sticky);
11090
11091 if (receiver == null) {
11092 return sticky;
11093 }
11094
11095 ReceiverList rl
11096 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11097 if (rl == null) {
11098 rl = new ReceiverList(this, callerApp,
11099 Binder.getCallingPid(),
11100 Binder.getCallingUid(), receiver);
11101 if (rl.app != null) {
11102 rl.app.receivers.add(rl);
11103 } else {
11104 try {
11105 receiver.asBinder().linkToDeath(rl, 0);
11106 } catch (RemoteException e) {
11107 return sticky;
11108 }
11109 rl.linkedToDeath = true;
11110 }
11111 mRegisteredReceivers.put(receiver.asBinder(), rl);
11112 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011113 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
11114 permission, callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011115 rl.add(bf);
11116 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011117 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011118 }
11119 mReceiverResolver.addFilter(bf);
11120
11121 // Enqueue broadcasts for all existing stickies that match
11122 // this filter.
11123 if (allSticky != null) {
11124 ArrayList receivers = new ArrayList();
11125 receivers.add(bf);
11126
11127 int N = allSticky.size();
11128 for (int i=0; i<N; i++) {
11129 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011130 BroadcastQueue queue = broadcastQueueForIntent(intent);
11131 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011132 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011133 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011134 queue.enqueueParallelBroadcastLocked(r);
11135 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011136 }
11137 }
11138
11139 return sticky;
11140 }
11141 }
11142
11143 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011144 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011145
Christopher Tatef46723b2012-01-26 14:19:24 -080011146 final long origId = Binder.clearCallingIdentity();
11147 try {
11148 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011149
Christopher Tatef46723b2012-01-26 14:19:24 -080011150 synchronized(this) {
11151 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011152 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011153 if (rl != null) {
11154 if (rl.curBroadcast != null) {
11155 BroadcastRecord r = rl.curBroadcast;
11156 final boolean doNext = finishReceiverLocked(
11157 receiver.asBinder(), r.resultCode, r.resultData,
11158 r.resultExtras, r.resultAbort, true);
11159 if (doNext) {
11160 doTrim = true;
11161 r.queue.processNextBroadcast(false);
11162 }
11163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011164
Christopher Tatef46723b2012-01-26 14:19:24 -080011165 if (rl.app != null) {
11166 rl.app.receivers.remove(rl);
11167 }
11168 removeReceiverLocked(rl);
11169 if (rl.linkedToDeath) {
11170 rl.linkedToDeath = false;
11171 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011173 }
11174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011175
Christopher Tatef46723b2012-01-26 14:19:24 -080011176 // If we actually concluded any broadcasts, we might now be able
11177 // to trim the recipients' apps from our working set
11178 if (doTrim) {
11179 trimApplications();
11180 return;
11181 }
11182
11183 } finally {
11184 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011186 }
11187
11188 void removeReceiverLocked(ReceiverList rl) {
11189 mRegisteredReceivers.remove(rl.receiver.asBinder());
11190 int N = rl.size();
11191 for (int i=0; i<N; i++) {
11192 mReceiverResolver.removeFilter(rl.get(i));
11193 }
11194 }
11195
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011196 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011197 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11198 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011199 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011200 try {
11201 r.thread.dispatchPackageBroadcast(cmd, packages);
11202 } catch (RemoteException ex) {
11203 }
11204 }
11205 }
11206 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011207
11208 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11209 int[] users) {
11210 List<ResolveInfo> receivers = null;
11211 try {
11212 HashSet<ComponentName> singleUserReceivers = null;
11213 boolean scannedFirstReceivers = false;
11214 for (int user : users) {
11215 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11216 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
11217 if (newReceivers != null && newReceivers.size() == 0) {
11218 newReceivers = null;
11219 }
11220 if (receivers == null) {
11221 receivers = newReceivers;
11222 } else if (newReceivers != null) {
11223 // We need to concatenate the additional receivers
11224 // found with what we have do far. This would be easy,
11225 // but we also need to de-dup any receivers that are
11226 // singleUser.
11227 if (!scannedFirstReceivers) {
11228 // Collect any single user receivers we had already retrieved.
11229 scannedFirstReceivers = true;
11230 for (int i=0; i<receivers.size(); i++) {
11231 ResolveInfo ri = receivers.get(i);
11232 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11233 ComponentName cn = new ComponentName(
11234 ri.activityInfo.packageName, ri.activityInfo.name);
11235 if (singleUserReceivers == null) {
11236 singleUserReceivers = new HashSet<ComponentName>();
11237 }
11238 singleUserReceivers.add(cn);
11239 }
11240 }
11241 }
11242 // Add the new results to the existing results, tracking
11243 // and de-dupping single user receivers.
11244 for (int i=0; i<newReceivers.size(); i++) {
11245 ResolveInfo ri = receivers.get(i);
11246 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11247 ComponentName cn = new ComponentName(
11248 ri.activityInfo.packageName, ri.activityInfo.name);
11249 if (singleUserReceivers == null) {
11250 singleUserReceivers = new HashSet<ComponentName>();
11251 }
11252 if (!singleUserReceivers.contains(cn)) {
11253 singleUserReceivers.add(cn);
11254 receivers.add(ri);
11255 }
11256 } else {
11257 receivers.add(ri);
11258 }
11259 }
11260 }
11261 }
11262 } catch (RemoteException ex) {
11263 // pm is in same process, this will never happen.
11264 }
11265 return receivers;
11266 }
11267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011268 private final int broadcastIntentLocked(ProcessRecord callerApp,
11269 String callerPackage, Intent intent, String resolvedType,
11270 IIntentReceiver resultTo, int resultCode, String resultData,
11271 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011272 boolean ordered, boolean sticky, int callingPid, int callingUid,
11273 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011274 intent = new Intent(intent);
11275
Dianne Hackborne7f97212011-02-24 14:40:20 -080011276 // By default broadcasts do not go to stopped apps.
11277 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11278
Joe Onorato8a9b2202010-02-26 18:56:32 -080011279 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011280 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011281 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011282 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011283 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011284 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011285
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011286 userId = handleIncomingUserLocked(callingPid, callingUid, userId,
11287 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011288
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011289 // Make sure that the user who is receiving this broadcast is started
11290 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011291 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011292 Slog.w(TAG, "Skipping broadcast of " + intent
11293 + ": user " + userId + " is stopped");
11294 return ActivityManager.BROADCAST_SUCCESS;
11295 }
11296
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011297 /*
11298 * Prevent non-system code (defined here to be non-persistent
11299 * processes) from sending protected broadcasts.
11300 */
11301 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11302 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11303 callingUid == 0) {
11304 // Always okay.
11305 } else if (callerApp == null || !callerApp.persistent) {
11306 try {
11307 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11308 intent.getAction())) {
11309 String msg = "Permission Denial: not allowed to send broadcast "
11310 + intent.getAction() + " from pid="
11311 + callingPid + ", uid=" + callingUid;
11312 Slog.w(TAG, msg);
11313 throw new SecurityException(msg);
11314 }
11315 } catch (RemoteException e) {
11316 Slog.w(TAG, "Remote exception", e);
11317 return ActivityManager.BROADCAST_SUCCESS;
11318 }
11319 }
11320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011321 // Handle special intents: if this broadcast is from the package
11322 // manager about a package being removed, we need to remove all of
11323 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011324 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011325 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011326 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11327 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011328 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011329 || uidRemoved) {
11330 if (checkComponentPermission(
11331 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011332 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011333 == PackageManager.PERMISSION_GRANTED) {
11334 if (uidRemoved) {
11335 final Bundle intentExtras = intent.getExtras();
11336 final int uid = intentExtras != null
11337 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11338 if (uid >= 0) {
11339 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11340 synchronized (bs) {
11341 bs.removeUidStatsLocked(uid);
11342 }
11343 }
11344 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011345 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011346 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011347 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011348 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11349 if (list != null && (list.length > 0)) {
11350 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011351 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011352 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011353 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011354 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011355 }
11356 } else {
11357 Uri data = intent.getData();
11358 String ssp;
11359 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11360 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11361 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011362 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11363 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011364 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011365 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011366 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011367 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011369 }
11370 }
11371 }
11372 } else {
11373 String msg = "Permission Denial: " + intent.getAction()
11374 + " broadcast from " + callerPackage + " (pid=" + callingPid
11375 + ", uid=" + callingUid + ")"
11376 + " requires "
11377 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011378 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379 throw new SecurityException(msg);
11380 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011381
11382 // Special case for adding a package: by default turn on compatibility
11383 // mode.
11384 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011385 Uri data = intent.getData();
11386 String ssp;
11387 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11388 mCompatModePackages.handlePackageAddedLocked(ssp,
11389 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011391 }
11392
11393 /*
11394 * If this is the time zone changed action, queue up a message that will reset the timezone
11395 * of all currently running processes. This message will get queued up before the broadcast
11396 * happens.
11397 */
11398 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11399 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11400 }
11401
Robert Greenwalt03595d02010-11-02 14:08:23 -070011402 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11403 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11404 }
11405
Robert Greenwalt434203a2010-10-11 16:00:27 -070011406 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11407 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11408 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11409 }
11410
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011411 // Add to the sticky list if requested.
11412 if (sticky) {
11413 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11414 callingPid, callingUid)
11415 != PackageManager.PERMISSION_GRANTED) {
11416 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11417 + callingPid + ", uid=" + callingUid
11418 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011419 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011420 throw new SecurityException(msg);
11421 }
11422 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011423 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011424 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011425 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011426 }
11427 if (intent.getComponent() != null) {
11428 throw new SecurityException(
11429 "Sticky broadcasts can't target a specific component");
11430 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011431 // We use userId directly here, since the "all" target is maintained
11432 // as a separate set of sticky broadcasts.
11433 if (userId != UserHandle.USER_ALL) {
11434 // But first, if this is not a broadcast to all users, then
11435 // make sure it doesn't conflict with an existing broadcast to
11436 // all users.
11437 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11438 UserHandle.USER_ALL);
11439 if (stickies != null) {
11440 ArrayList<Intent> list = stickies.get(intent.getAction());
11441 if (list != null) {
11442 int N = list.size();
11443 int i;
11444 for (i=0; i<N; i++) {
11445 if (intent.filterEquals(list.get(i))) {
11446 throw new IllegalArgumentException(
11447 "Sticky broadcast " + intent + " for user "
11448 + userId + " conflicts with existing global broadcast");
11449 }
11450 }
11451 }
11452 }
11453 }
11454 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11455 if (stickies == null) {
11456 stickies = new HashMap<String, ArrayList<Intent>>();
11457 mStickyBroadcasts.put(userId, stickies);
11458 }
11459 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011460 if (list == null) {
11461 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011462 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011463 }
11464 int N = list.size();
11465 int i;
11466 for (i=0; i<N; i++) {
11467 if (intent.filterEquals(list.get(i))) {
11468 // This sticky already exists, replace it.
11469 list.set(i, new Intent(intent));
11470 break;
11471 }
11472 }
11473 if (i >= N) {
11474 list.add(new Intent(intent));
11475 }
11476 }
11477
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011478 int[] users;
11479 if (userId == UserHandle.USER_ALL) {
11480 // Caller wants broadcast to go to all started users.
11481 users = new int[mStartedUsers.size()];
11482 for (int i=0; i<mStartedUsers.size(); i++) {
11483 users[i] = mStartedUsers.keyAt(i);
11484 }
11485 } else {
11486 // Caller wants broadcast to go to one specific user.
11487 users = new int[] {userId};
11488 }
11489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011490 // Figure out who all will receive this broadcast.
11491 List receivers = null;
11492 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011493 // Need to resolve the intent to interested receivers...
11494 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11495 == 0) {
11496 receivers = collectReceiverComponents(intent, resolvedType, users);
11497 }
11498 if (intent.getComponent() == null) {
11499 registeredReceivers = mReceiverResolver.queryIntent(intent,
11500 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011501 }
11502
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011503 final boolean replacePending =
11504 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11505
Joe Onorato8a9b2202010-02-26 18:56:32 -080011506 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011507 + " replacePending=" + replacePending);
11508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011509 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11510 if (!ordered && NR > 0) {
11511 // If we are not serializing this broadcast, then send the
11512 // registered receivers separately so they don't wait for the
11513 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011514 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11515 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011516 callerPackage, callingPid, callingUid, requiredPermission,
11517 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011518 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011519 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011520 TAG, "Enqueueing parallel broadcast " + r);
11521 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011522 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011523 queue.enqueueParallelBroadcastLocked(r);
11524 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011526 registeredReceivers = null;
11527 NR = 0;
11528 }
11529
11530 // Merge into one list.
11531 int ir = 0;
11532 if (receivers != null) {
11533 // A special case for PACKAGE_ADDED: do not allow the package
11534 // being added to see this broadcast. This prevents them from
11535 // using this as a back door to get run as soon as they are
11536 // installed. Maybe in the future we want to have a special install
11537 // broadcast or such for apps, but we'd like to deliberately make
11538 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011539 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011540 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11541 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11542 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011543 Uri data = intent.getData();
11544 if (data != null) {
11545 String pkgName = data.getSchemeSpecificPart();
11546 if (pkgName != null) {
11547 skipPackages = new String[] { pkgName };
11548 }
11549 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011550 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011551 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011552 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011553 if (skipPackages != null && (skipPackages.length > 0)) {
11554 for (String skipPackage : skipPackages) {
11555 if (skipPackage != null) {
11556 int NT = receivers.size();
11557 for (int it=0; it<NT; it++) {
11558 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11559 if (curt.activityInfo.packageName.equals(skipPackage)) {
11560 receivers.remove(it);
11561 it--;
11562 NT--;
11563 }
11564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011565 }
11566 }
11567 }
11568
11569 int NT = receivers != null ? receivers.size() : 0;
11570 int it = 0;
11571 ResolveInfo curt = null;
11572 BroadcastFilter curr = null;
11573 while (it < NT && ir < NR) {
11574 if (curt == null) {
11575 curt = (ResolveInfo)receivers.get(it);
11576 }
11577 if (curr == null) {
11578 curr = registeredReceivers.get(ir);
11579 }
11580 if (curr.getPriority() >= curt.priority) {
11581 // Insert this broadcast record into the final list.
11582 receivers.add(it, curr);
11583 ir++;
11584 curr = null;
11585 it++;
11586 NT++;
11587 } else {
11588 // Skip to the next ResolveInfo in the final list.
11589 it++;
11590 curt = null;
11591 }
11592 }
11593 }
11594 while (ir < NR) {
11595 if (receivers == null) {
11596 receivers = new ArrayList();
11597 }
11598 receivers.add(registeredReceivers.get(ir));
11599 ir++;
11600 }
11601
11602 if ((receivers != null && receivers.size() > 0)
11603 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011604 BroadcastQueue queue = broadcastQueueForIntent(intent);
11605 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011606 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011607 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011608 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011609 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011610 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011611 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011612 if (DEBUG_BROADCAST) {
11613 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011614 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011615 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011616 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011617 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011618 queue.enqueueOrderedBroadcastLocked(r);
11619 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011621 }
11622
Dianne Hackborna4972e92012-03-14 10:38:05 -070011623 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011624 }
11625
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011626 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011627 // Refuse possible leaked file descriptors
11628 if (intent != null && intent.hasFileDescriptors() == true) {
11629 throw new IllegalArgumentException("File descriptors passed in Intent");
11630 }
11631
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011632 int flags = intent.getFlags();
11633
11634 if (!mProcessesReady) {
11635 // if the caller really truly claims to know what they're doing, go
11636 // ahead and allow the broadcast without launching any receivers
11637 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11638 intent = new Intent(intent);
11639 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11640 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11641 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11642 + " before boot completion");
11643 throw new IllegalStateException("Cannot broadcast before boot completed");
11644 }
11645 }
11646
11647 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11648 throw new IllegalArgumentException(
11649 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11650 }
11651
11652 return intent;
11653 }
11654
11655 public final int broadcastIntent(IApplicationThread caller,
11656 Intent intent, String resolvedType, IIntentReceiver resultTo,
11657 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011658 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011659 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011660 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011661 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011663 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11664 final int callingPid = Binder.getCallingPid();
11665 final int callingUid = Binder.getCallingUid();
11666 final long origId = Binder.clearCallingIdentity();
11667 int res = broadcastIntentLocked(callerApp,
11668 callerApp != null ? callerApp.info.packageName : null,
11669 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011670 resultCode, resultData, map, requiredPermission, serialized, sticky,
11671 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011672 Binder.restoreCallingIdentity(origId);
11673 return res;
11674 }
11675 }
11676
11677 int broadcastIntentInPackage(String packageName, int uid,
11678 Intent intent, String resolvedType, IIntentReceiver resultTo,
11679 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011680 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011681 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011682 intent = verifyBroadcastLocked(intent);
11683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011684 final long origId = Binder.clearCallingIdentity();
11685 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11686 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011687 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011688 Binder.restoreCallingIdentity(origId);
11689 return res;
11690 }
11691 }
11692
Amith Yamasani742a6712011-05-04 14:49:28 -070011693 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011694 // Refuse possible leaked file descriptors
11695 if (intent != null && intent.hasFileDescriptors() == true) {
11696 throw new IllegalArgumentException("File descriptors passed in Intent");
11697 }
11698
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011699 userId = handleIncomingUserLocked(Binder.getCallingPid(),
11700 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011702 synchronized(this) {
11703 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11704 != PackageManager.PERMISSION_GRANTED) {
11705 String msg = "Permission Denial: unbroadcastIntent() from pid="
11706 + Binder.getCallingPid()
11707 + ", uid=" + Binder.getCallingUid()
11708 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011709 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011710 throw new SecurityException(msg);
11711 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011712 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11713 if (stickies != null) {
11714 ArrayList<Intent> list = stickies.get(intent.getAction());
11715 if (list != null) {
11716 int N = list.size();
11717 int i;
11718 for (i=0; i<N; i++) {
11719 if (intent.filterEquals(list.get(i))) {
11720 list.remove(i);
11721 break;
11722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011723 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011724 if (list.size() <= 0) {
11725 stickies.remove(intent.getAction());
11726 }
11727 }
11728 if (stickies.size() <= 0) {
11729 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011730 }
11731 }
11732 }
11733 }
11734
11735 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11736 String resultData, Bundle resultExtras, boolean resultAbort,
11737 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011738 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11739 if (r == null) {
11740 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011741 return false;
11742 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011743
Christopher Tatef46723b2012-01-26 14:19:24 -080011744 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11745 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011746 }
11747
11748 public void finishReceiver(IBinder who, int resultCode, String resultData,
11749 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011750 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011751
11752 // Refuse possible leaked file descriptors
11753 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11754 throw new IllegalArgumentException("File descriptors passed in Bundle");
11755 }
11756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011757 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011758 try {
11759 boolean doNext = false;
11760 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011761
Christopher Tatef46723b2012-01-26 14:19:24 -080011762 synchronized(this) {
11763 r = broadcastRecordForReceiverLocked(who);
11764 if (r != null) {
11765 doNext = r.queue.finishReceiverLocked(r, resultCode,
11766 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011768 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011769
Christopher Tatef46723b2012-01-26 14:19:24 -080011770 if (doNext) {
11771 r.queue.processNextBroadcast(false);
11772 }
11773 trimApplications();
11774 } finally {
11775 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011779 // =========================================================
11780 // INSTRUMENTATION
11781 // =========================================================
11782
11783 public boolean startInstrumentation(ComponentName className,
11784 String profileFile, int flags, Bundle arguments,
11785 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011786 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011787 // Refuse possible leaked file descriptors
11788 if (arguments != null && arguments.hasFileDescriptors()) {
11789 throw new IllegalArgumentException("File descriptors passed in Bundle");
11790 }
11791
11792 synchronized(this) {
11793 InstrumentationInfo ii = null;
11794 ApplicationInfo ai = null;
11795 try {
11796 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011797 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011798 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011799 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011800 } catch (PackageManager.NameNotFoundException e) {
11801 }
11802 if (ii == null) {
11803 reportStartInstrumentationFailure(watcher, className,
11804 "Unable to find instrumentation info for: " + className);
11805 return false;
11806 }
11807 if (ai == null) {
11808 reportStartInstrumentationFailure(watcher, className,
11809 "Unable to find instrumentation target package: " + ii.targetPackage);
11810 return false;
11811 }
11812
11813 int match = mContext.getPackageManager().checkSignatures(
11814 ii.targetPackage, ii.packageName);
11815 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11816 String msg = "Permission Denial: starting instrumentation "
11817 + className + " from pid="
11818 + Binder.getCallingPid()
11819 + ", uid=" + Binder.getCallingPid()
11820 + " not allowed because package " + ii.packageName
11821 + " does not have a signature matching the target "
11822 + ii.targetPackage;
11823 reportStartInstrumentationFailure(watcher, className, msg);
11824 throw new SecurityException(msg);
11825 }
11826
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011827 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011828 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070011829 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070011830 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011831 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011832 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011833 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011834 app.instrumentationProfileFile = profileFile;
11835 app.instrumentationArguments = arguments;
11836 app.instrumentationWatcher = watcher;
11837 app.instrumentationResultClass = className;
11838 Binder.restoreCallingIdentity(origId);
11839 }
11840
11841 return true;
11842 }
11843
11844 /**
11845 * Report errors that occur while attempting to start Instrumentation. Always writes the
11846 * error to the logs, but if somebody is watching, send the report there too. This enables
11847 * the "am" command to report errors with more information.
11848 *
11849 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11850 * @param cn The component name of the instrumentation.
11851 * @param report The error report.
11852 */
11853 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11854 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011855 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011856 try {
11857 if (watcher != null) {
11858 Bundle results = new Bundle();
11859 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11860 results.putString("Error", report);
11861 watcher.instrumentationStatus(cn, -1, results);
11862 }
11863 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011864 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011865 }
11866 }
11867
11868 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
11869 if (app.instrumentationWatcher != null) {
11870 try {
11871 // NOTE: IInstrumentationWatcher *must* be oneway here
11872 app.instrumentationWatcher.instrumentationFinished(
11873 app.instrumentationClass,
11874 resultCode,
11875 results);
11876 } catch (RemoteException e) {
11877 }
11878 }
11879 app.instrumentationWatcher = null;
11880 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011881 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011882 app.instrumentationProfileFile = null;
11883 app.instrumentationArguments = null;
11884
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011885 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011886 }
11887
11888 public void finishInstrumentation(IApplicationThread target,
11889 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011890 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011891 // Refuse possible leaked file descriptors
11892 if (results != null && results.hasFileDescriptors()) {
11893 throw new IllegalArgumentException("File descriptors passed in Intent");
11894 }
11895
11896 synchronized(this) {
11897 ProcessRecord app = getRecordForAppLocked(target);
11898 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011899 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011900 return;
11901 }
11902 final long origId = Binder.clearCallingIdentity();
11903 finishInstrumentationLocked(app, resultCode, results);
11904 Binder.restoreCallingIdentity(origId);
11905 }
11906 }
11907
11908 // =========================================================
11909 // CONFIGURATION
11910 // =========================================================
11911
11912 public ConfigurationInfo getDeviceConfigurationInfo() {
11913 ConfigurationInfo config = new ConfigurationInfo();
11914 synchronized (this) {
11915 config.reqTouchScreen = mConfiguration.touchscreen;
11916 config.reqKeyboardType = mConfiguration.keyboard;
11917 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011918 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
11919 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011920 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
11921 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011922 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
11923 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011924 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
11925 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070011926 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011927 }
11928 return config;
11929 }
11930
11931 public Configuration getConfiguration() {
11932 Configuration ci;
11933 synchronized(this) {
11934 ci = new Configuration(mConfiguration);
11935 }
11936 return ci;
11937 }
11938
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011939 public void updatePersistentConfiguration(Configuration values) {
11940 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11941 "updateConfiguration()");
11942 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
11943 "updateConfiguration()");
11944 if (values == null) {
11945 throw new NullPointerException("Configuration must not be null");
11946 }
11947
11948 synchronized(this) {
11949 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080011950 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011951 Binder.restoreCallingIdentity(origId);
11952 }
11953 }
11954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011955 public void updateConfiguration(Configuration values) {
11956 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11957 "updateConfiguration()");
11958
11959 synchronized(this) {
11960 if (values == null && mWindowManager != null) {
11961 // sentinel: fetch the current configuration from the window manager
11962 values = mWindowManager.computeNewConfiguration();
11963 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070011964
11965 if (mWindowManager != null) {
11966 mProcessList.applyDisplaySize(mWindowManager);
11967 }
11968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011969 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011970 if (values != null) {
11971 Settings.System.clearConfiguration(values);
11972 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080011973 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011974 Binder.restoreCallingIdentity(origId);
11975 }
11976 }
11977
11978 /**
11979 * Do either or both things: (1) change the current configuration, and (2)
11980 * make sure the given activity is running with the (now) current
11981 * configuration. Returns true if the activity has been left running, or
11982 * false if <var>starting</var> is being destroyed to match the new
11983 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011984 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011985 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011986 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080011987 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070011988 // do nothing if we are headless
11989 if (mHeadless) return true;
11990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011991 int changes = 0;
11992
11993 boolean kept = true;
11994
11995 if (values != null) {
11996 Configuration newConfig = new Configuration(mConfiguration);
11997 changes = newConfig.updateFrom(values);
11998 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011999 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012000 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012001 }
12002
Doug Zongker2bec3d42009-12-04 12:52:44 -080012003 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012004
Dianne Hackborn813075a62011-11-14 17:45:19 -080012005 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012006 saveLocaleLocked(values.locale,
12007 !values.locale.equals(mConfiguration.locale),
12008 values.userSetLocale);
12009 }
12010
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012011 mConfigurationSeq++;
12012 if (mConfigurationSeq <= 0) {
12013 mConfigurationSeq = 1;
12014 }
12015 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012016 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012017 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012018
12019 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012020
12021 // TODO: If our config changes, should we auto dismiss any currently
12022 // showing dialogs?
12023 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012024
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012025 AttributeCache ac = AttributeCache.instance();
12026 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012027 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012029
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012030 // Make sure all resources in our process are updated
12031 // right now, so that anyone who is going to retrieve
12032 // resource values after we return will be sure to get
12033 // the new ones. This is especially important during
12034 // boot, where the first config change needs to guarantee
12035 // all resources have that config before following boot
12036 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012037 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012038
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012039 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012040 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012041 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012042 mHandler.sendMessage(msg);
12043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012044
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012045 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12046 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012047 try {
12048 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012049 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012050 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012051 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012052 }
12053 } catch (Exception e) {
12054 }
12055 }
12056 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012057 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12058 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012059 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012060 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012061 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12062 broadcastIntentLocked(null, null,
12063 new Intent(Intent.ACTION_LOCALE_CHANGED),
12064 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012065 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012067 }
12068 }
12069
12070 if (changes != 0 && starting == null) {
12071 // If the configuration changed, and the caller is not already
12072 // in the process of starting an activity, then find the top
12073 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012074 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012075 }
12076
12077 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012078 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012079 // And we need to make sure at this point that all other activities
12080 // are made visible with the correct configuration.
12081 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012082 }
12083
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012084 if (values != null && mWindowManager != null) {
12085 mWindowManager.setNewConfiguration(mConfiguration);
12086 }
12087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012088 return kept;
12089 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012090
12091 /**
12092 * Decide based on the configuration whether we should shouw the ANR,
12093 * crash, etc dialogs. The idea is that if there is no affordnace to
12094 * press the on-screen buttons, we shouldn't show the dialog.
12095 *
12096 * A thought: SystemUI might also want to get told about this, the Power
12097 * dialog / global actions also might want different behaviors.
12098 */
12099 private static final boolean shouldShowDialogs(Configuration config) {
12100 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12101 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012103
12104 /**
12105 * Save the locale. You must be inside a synchronized (this) block.
12106 */
12107 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12108 if(isDiff) {
12109 SystemProperties.set("user.language", l.getLanguage());
12110 SystemProperties.set("user.region", l.getCountry());
12111 }
12112
12113 if(isPersist) {
12114 SystemProperties.set("persist.sys.language", l.getLanguage());
12115 SystemProperties.set("persist.sys.country", l.getCountry());
12116 SystemProperties.set("persist.sys.localevar", l.getVariant());
12117 }
12118 }
12119
Adam Powelldd8fab22012-03-22 17:47:27 -070012120 @Override
12121 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12122 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012123 return srec != null && srec.task.affinity != null &&
12124 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012125 }
12126
12127 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12128 Intent resultData) {
12129 ComponentName dest = destIntent.getComponent();
12130
12131 synchronized (this) {
12132 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012133 if (srec == null) {
12134 return false;
12135 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012136 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12137 final int start = history.indexOf(srec);
12138 if (start < 0) {
12139 // Current activity is not in history stack; do nothing.
12140 return false;
12141 }
12142 int finishTo = start - 1;
12143 ActivityRecord parent = null;
12144 boolean foundParentInTask = false;
12145 if (dest != null) {
12146 TaskRecord tr = srec.task;
12147 for (int i = start - 1; i >= 0; i--) {
12148 ActivityRecord r = history.get(i);
12149 if (tr != r.task) {
12150 // Couldn't find parent in the same task; stop at the one above this.
12151 // (Root of current task; in-app "home" behavior)
12152 // Always at least finish the current activity.
12153 finishTo = Math.min(start - 1, i + 1);
12154 parent = history.get(finishTo);
12155 break;
12156 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12157 r.info.name.equals(dest.getClassName())) {
12158 finishTo = i;
12159 parent = r;
12160 foundParentInTask = true;
12161 break;
12162 }
12163 }
12164 }
12165
12166 if (mController != null) {
12167 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12168 if (next != null) {
12169 // ask watcher if this is allowed
12170 boolean resumeOK = true;
12171 try {
12172 resumeOK = mController.activityResuming(next.packageName);
12173 } catch (RemoteException e) {
12174 mController = null;
12175 }
12176
12177 if (!resumeOK) {
12178 return false;
12179 }
12180 }
12181 }
12182 final long origId = Binder.clearCallingIdentity();
12183 for (int i = start; i > finishTo; i--) {
12184 ActivityRecord r = history.get(i);
12185 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
12186 "navigate-up");
12187 // Only return the supplied result for the first activity finished
12188 resultCode = Activity.RESULT_CANCELED;
12189 resultData = null;
12190 }
12191
12192 if (parent != null && foundParentInTask) {
12193 final int parentLaunchMode = parent.info.launchMode;
12194 final int destIntentFlags = destIntent.getFlags();
12195 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12196 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12197 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12198 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012199 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012200 } else {
12201 try {
12202 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012203 destIntent.getComponent(), 0, UserHandle.getCallingUserId());
Adam Powelldd8fab22012-03-22 17:47:27 -070012204 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12205 null, aInfo, parent.appToken, null,
12206 0, -1, parent.launchedFromUid, 0, null, true, null);
12207 foundParentInTask = res == ActivityManager.START_SUCCESS;
12208 } catch (RemoteException e) {
12209 foundParentInTask = false;
12210 }
12211 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
12212 resultData, "navigate-up");
12213 }
12214 }
12215 Binder.restoreCallingIdentity(origId);
12216 return foundParentInTask;
12217 }
12218 }
12219
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012220 public int getLaunchedFromUid(IBinder activityToken) {
12221 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12222 if (srec == null) {
12223 return -1;
12224 }
12225 return srec.launchedFromUid;
12226 }
12227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012228 // =========================================================
12229 // LIFETIME MANAGEMENT
12230 // =========================================================
12231
Christopher Tatef46723b2012-01-26 14:19:24 -080012232 // Returns which broadcast queue the app is the current [or imminent] receiver
12233 // on, or 'null' if the app is not an active broadcast recipient.
12234 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12235 BroadcastRecord r = app.curReceiver;
12236 if (r != null) {
12237 return r.queue;
12238 }
12239
12240 // It's not the current receiver, but it might be starting up to become one
12241 synchronized (this) {
12242 for (BroadcastQueue queue : mBroadcastQueues) {
12243 r = queue.mPendingBroadcast;
12244 if (r != null && r.curApp == app) {
12245 // found it; report which queue it's in
12246 return queue;
12247 }
12248 }
12249 }
12250
12251 return null;
12252 }
12253
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012254 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012255 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012256 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012257 // This adjustment has already been computed. If we are calling
12258 // from the top, we may have already computed our adjustment with
12259 // an earlier hidden adjustment that isn't really for us... if
12260 // so, use the new hidden adjustment.
12261 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012262 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
12263 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012264 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012265 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012266 }
12267
12268 if (app.thread == null) {
12269 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012270 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012271 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012272 }
12273
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012274 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12275 app.adjSource = null;
12276 app.adjTarget = null;
12277 app.empty = false;
12278 app.hidden = false;
12279
12280 final int activitiesSize = app.activities.size();
12281
Dianne Hackborn7d608422011-08-07 16:24:18 -070012282 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012283 // The max adjustment doesn't allow this app to be anything
12284 // below foreground, so it is not worth doing work for it.
12285 app.adjType = "fixed";
12286 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012287 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012288 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012289 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012290 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012291 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012292 // System process can do UI, and when they do we want to have
12293 // them trim their memory after the user leaves the UI. To
12294 // facilitate this, here we need to determine whether or not it
12295 // is currently showing UI.
12296 app.systemNoUi = true;
12297 if (app == TOP_APP) {
12298 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012299 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012300 } else if (activitiesSize > 0) {
12301 for (int j = 0; j < activitiesSize; j++) {
12302 final ActivityRecord r = app.activities.get(j);
12303 if (r.visible) {
12304 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012305 }
12306 if (r.app == app) {
12307 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012308 }
12309 }
12310 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012311 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012312 }
12313
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012314 app.keeping = false;
12315 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012316 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012317
The Android Open Source Project4df24232009-03-05 14:34:35 -080012318 // Determine the importance of the process, starting with most
12319 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012320 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012321 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012322 boolean foregroundActivities = false;
12323 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012324 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012325 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012326 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012327 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012328 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012329 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012330 foregroundActivities = true;
12331 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012332 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012333 } else if (app.instrumentationClass != null) {
12334 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012335 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012336 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012337 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012338 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012339 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012340 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012341 // counts as being in the foreground for OOM killer purposes.
12342 // It's placed in a sched group based on the nature of the
12343 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012344 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012345 schedGroup = (queue == mFgBroadcastQueue)
12346 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012347 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012348 } else if (app.executingServices.size() > 0) {
12349 // An app that is currently executing a service callback also
12350 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012351 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012352 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012353 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012354 } else {
12355 // Assume process is hidden (has activities); we will correct
12356 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012357 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012358 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012359 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012360 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012361 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012362
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012363 boolean hasStoppingActivities = false;
12364
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012365 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012366 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012367 for (int j = 0; j < activitiesSize; j++) {
12368 final ActivityRecord r = app.activities.get(j);
12369 if (r.visible) {
12370 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012371 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12372 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012373 app.adjType = "visible";
12374 }
12375 schedGroup = Process.THREAD_GROUP_DEFAULT;
12376 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012377 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012378 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012379 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012380 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012381 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12382 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012383 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012384 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012385 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012386 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012387 } else if (r.state == ActivityState.STOPPING) {
12388 // We will apply the actual adjustment later, because
12389 // we want to allow this process to immediately go through
12390 // any memory trimming that is in effect.
12391 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012392 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012393 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012394 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012395 if (r.app == app) {
12396 app.hasActivities = true;
12397 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012398 }
12399 }
12400
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012401 if (adj == hiddenAdj && !app.hasActivities) {
12402 // Whoops, this process is completely empty as far as we know
12403 // at this point.
12404 adj = emptyAdj;
12405 app.empty = true;
12406 app.adjType = "bg-empty";
12407 }
12408
Dianne Hackborn7d608422011-08-07 16:24:18 -070012409 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012410 if (app.foregroundServices) {
12411 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012412 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012413 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012414 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012415 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012416 } else if (app.forcingToForeground != null) {
12417 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012418 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012419 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012420 app.adjType = "force-foreground";
12421 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012422 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012423 }
12424 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012425
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012426 if (app.foregroundServices) {
12427 interesting = true;
12428 }
12429
Dianne Hackborn7d608422011-08-07 16:24:18 -070012430 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012431 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012432 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012433 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012434 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012435 app.adjType = "heavy";
12436 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012437
Dianne Hackborn7d608422011-08-07 16:24:18 -070012438 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012439 // This process is hosting what we currently consider to be the
12440 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012441 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012442 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012443 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012444 app.adjType = "home";
12445 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012446
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012447 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12448 && app.activities.size() > 0) {
12449 // This was the previous process that showed UI to the user.
12450 // We want to try to keep it around more aggressively, to give
12451 // a good experience around switching between two apps.
12452 adj = ProcessList.PREVIOUS_APP_ADJ;
12453 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12454 app.hidden = false;
12455 app.adjType = "previous";
12456 }
12457
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012458 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12459 + " reason=" + app.adjType);
12460
The Android Open Source Project4df24232009-03-05 14:34:35 -080012461 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012462 // there are applications dependent on our services or providers, but
12463 // this gives us a baseline and makes sure we don't get into an
12464 // infinite recursion.
12465 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012466 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012467
Christopher Tate6fa95972009-06-05 18:43:55 -070012468 if (mBackupTarget != null && app == mBackupTarget.app) {
12469 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012470 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012471 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012472 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012473 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012474 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012475 }
12476 }
12477
Dianne Hackborn7d608422011-08-07 16:24:18 -070012478 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012479 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012480 final long now = SystemClock.uptimeMillis();
12481 // This process is more important if the top activity is
12482 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012483 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012484 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012485 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012486 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012487 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012488 // If this process has shown some UI, let it immediately
12489 // go to the LRU list because it may be pretty heavy with
12490 // UI stuff. We'll tag it with a label just to help
12491 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012492 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012493 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012494 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012495 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012496 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012497 // This service has seen some activity within
12498 // recent memory, so we will keep its process ahead
12499 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012500 if (adj > ProcessList.SERVICE_ADJ) {
12501 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012502 app.adjType = "started-services";
12503 app.hidden = false;
12504 }
12505 }
12506 // If we have let the service slide into the background
12507 // state, still have some text describing what it is doing
12508 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012509 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012510 app.adjType = "started-bg-services";
12511 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012512 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012513 // Don't kill this process because it is doing work; it
12514 // has said it is doing work.
12515 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012516 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012517 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012518 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012519 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012520 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012521 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012522 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012523 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012524 // XXX should compute this based on the max of
12525 // all connected clients.
12526 ConnectionRecord cr = clist.get(i);
12527 if (cr.binding.client == app) {
12528 // Binding to ourself is not interesting.
12529 continue;
12530 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012531 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012532 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012533 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012534 int myHiddenAdj = hiddenAdj;
12535 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012536 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012537 myHiddenAdj = client.hiddenAdj;
12538 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012539 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012540 }
12541 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012542 int myEmptyAdj = emptyAdj;
12543 if (myEmptyAdj > client.emptyAdj) {
12544 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12545 myEmptyAdj = client.emptyAdj;
12546 } else {
12547 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12548 }
12549 }
12550 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12551 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012552 String adjType = null;
12553 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12554 // Not doing bind OOM management, so treat
12555 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012556 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012557 // If this process has shown some UI, let it immediately
12558 // go to the LRU list because it may be pretty heavy with
12559 // UI stuff. We'll tag it with a label just to help
12560 // debug and understand what is going on.
12561 if (adj > clientAdj) {
12562 adjType = "bound-bg-ui-services";
12563 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012564 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012565 clientAdj = adj;
12566 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012567 if (now >= (s.lastActivity
12568 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012569 // This service has not seen activity within
12570 // recent memory, so allow it to drop to the
12571 // LRU list if there is no other reason to keep
12572 // it around. We'll also tag it with a label just
12573 // to help debug and undertand what is going on.
12574 if (adj > clientAdj) {
12575 adjType = "bound-bg-services";
12576 }
12577 clientAdj = adj;
12578 }
12579 }
12580 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012581 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012582 // If this process has recently shown UI, and
12583 // the process that is binding to it is less
12584 // important than being visible, then we don't
12585 // care about the binding as much as we care
12586 // about letting this process get into the LRU
12587 // list to be killed and restarted if needed for
12588 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012589 if (app.hasShownUi && app != mHomeProcess
12590 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012591 adjType = "bound-bg-ui-services";
12592 } else {
12593 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12594 |Context.BIND_IMPORTANT)) != 0) {
12595 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012596 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12597 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12598 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12599 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12600 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012601 adj = clientAdj;
12602 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012603 app.pendingUiClean = true;
12604 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12605 adj = ProcessList.VISIBLE_APP_ADJ;
12606 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012607 }
12608 if (!client.hidden) {
12609 app.hidden = false;
12610 }
12611 if (client.keeping) {
12612 app.keeping = true;
12613 }
12614 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012615 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012616 }
12617 if (adjType != null) {
12618 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012619 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12620 .REASON_SERVICE_IN_USE;
12621 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012622 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012623 app.adjTarget = s.name;
12624 }
12625 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12626 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12627 schedGroup = Process.THREAD_GROUP_DEFAULT;
12628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012629 }
12630 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012631 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12632 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012633 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012634 (a.visible || a.state == ActivityState.RESUMED
12635 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012636 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012637 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12638 schedGroup = Process.THREAD_GROUP_DEFAULT;
12639 }
12640 app.hidden = false;
12641 app.adjType = "service";
12642 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12643 .REASON_SERVICE_IN_USE;
12644 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012645 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012646 app.adjTarget = s.name;
12647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012649 }
12650 }
12651 }
12652 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012653
Dianne Hackborn287952c2010-09-22 22:34:31 -070012654 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012655 // would like to avoid killing it unless it would prevent the current
12656 // application from running. By default we put the process in
12657 // with the rest of the background processes; as we scan through
12658 // its services we may bump it up from there.
12659 if (adj > hiddenAdj) {
12660 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012661 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012662 app.adjType = "bg-services";
12663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012664 }
12665
Dianne Hackborn7d608422011-08-07 16:24:18 -070012666 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012667 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012668 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012669 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012670 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012671 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012672 for (int i = cpr.connections.size()-1;
12673 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12674 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12675 i--) {
12676 ContentProviderConnection conn = cpr.connections.get(i);
12677 ProcessRecord client = conn.client;
12678 if (client == app) {
12679 // Being our own client is not interesting.
12680 continue;
12681 }
12682 int myHiddenAdj = hiddenAdj;
12683 if (myHiddenAdj > client.hiddenAdj) {
12684 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12685 myHiddenAdj = client.hiddenAdj;
12686 } else {
12687 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012688 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012689 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012690 int myEmptyAdj = emptyAdj;
12691 if (myEmptyAdj > client.emptyAdj) {
12692 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12693 myEmptyAdj = client.emptyAdj;
12694 } else {
12695 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12696 }
12697 }
12698 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12699 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012700 if (adj > clientAdj) {
12701 if (app.hasShownUi && app != mHomeProcess
12702 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12703 app.adjType = "bg-ui-provider";
12704 } else {
12705 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12706 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12707 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012708 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012709 if (!client.hidden) {
12710 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012711 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012712 if (client.keeping) {
12713 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012714 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012715 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12716 .REASON_PROVIDER_IN_USE;
12717 app.adjSource = client;
12718 app.adjSourceOom = clientAdj;
12719 app.adjTarget = cpr.name;
12720 }
12721 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12722 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012723 }
12724 }
12725 // If the provider has external (non-framework) process
12726 // dependencies, ensure that its adjustment is at least
12727 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012728 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012729 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12730 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012731 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012732 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012733 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012734 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012735 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012736 }
12737 }
12738 }
12739 }
12740
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012741 if (adj == ProcessList.SERVICE_ADJ) {
12742 if (doingAll) {
12743 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12744 mNewNumServiceProcs++;
12745 }
12746 if (app.serviceb) {
12747 adj = ProcessList.SERVICE_B_ADJ;
12748 }
12749 } else {
12750 app.serviceb = false;
12751 }
12752
12753 app.nonStoppingAdj = adj;
12754
12755 if (hasStoppingActivities) {
12756 // Only upgrade adjustment.
12757 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12758 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12759 app.adjType = "stopping";
12760 }
12761 }
12762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012763 app.curRawAdj = adj;
12764
Joe Onorato8a9b2202010-02-26 18:56:32 -080012765 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012766 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12767 if (adj > app.maxAdj) {
12768 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012769 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012770 schedGroup = Process.THREAD_GROUP_DEFAULT;
12771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012772 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012773 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012774 app.keeping = true;
12775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012776
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012777 if (app.hasAboveClient) {
12778 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12779 // then we need to drop its adjustment to be lower than the service's
12780 // in order to honor the request. We want to drop it by one adjustment
12781 // level... but there is special meaning applied to various levels so
12782 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012783 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012784 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012785 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12786 adj = ProcessList.VISIBLE_APP_ADJ;
12787 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12788 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12789 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12790 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012791 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012792 adj++;
12793 }
12794 }
12795
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012796 int importance = app.memImportance;
12797 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12798 app.curAdj = adj;
12799 app.curSchedGroup = schedGroup;
12800 if (!interesting) {
12801 // For this reporting, if there is not something explicitly
12802 // interesting in this process then we will push it to the
12803 // background importance.
12804 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12805 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12806 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12807 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12808 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12809 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12810 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12811 } else if (adj >= ProcessList.SERVICE_ADJ) {
12812 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12813 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12814 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12815 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12816 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
12817 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
12818 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
12819 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
12820 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
12821 } else {
12822 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
12823 }
12824 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012825
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012826 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
12827 if (foregroundActivities != app.foregroundActivities) {
12828 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
12829 }
12830 if (changes != 0) {
12831 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
12832 app.memImportance = importance;
12833 app.foregroundActivities = foregroundActivities;
12834 int i = mPendingProcessChanges.size()-1;
12835 ProcessChangeItem item = null;
12836 while (i >= 0) {
12837 item = mPendingProcessChanges.get(i);
12838 if (item.pid == app.pid) {
12839 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
12840 break;
12841 }
12842 i--;
12843 }
12844 if (i < 0) {
12845 // No existing item in pending changes; need a new one.
12846 final int NA = mAvailProcessChanges.size();
12847 if (NA > 0) {
12848 item = mAvailProcessChanges.remove(NA-1);
12849 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
12850 } else {
12851 item = new ProcessChangeItem();
12852 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
12853 }
12854 item.changes = 0;
12855 item.pid = app.pid;
12856 item.uid = app.info.uid;
12857 if (mPendingProcessChanges.size() == 0) {
12858 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
12859 "*** Enqueueing dispatch processes changed!");
12860 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
12861 }
12862 mPendingProcessChanges.add(item);
12863 }
12864 item.changes |= changes;
12865 item.importance = importance;
12866 item.foregroundActivities = foregroundActivities;
12867 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
12868 + Integer.toHexString(System.identityHashCode(item))
12869 + " " + app.toShortString() + ": changes=" + item.changes
12870 + " importance=" + item.importance
12871 + " foreground=" + item.foregroundActivities
12872 + " type=" + app.adjType + " source=" + app.adjSource
12873 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012874 }
12875
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012876 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012877 }
12878
12879 /**
12880 * Ask a given process to GC right now.
12881 */
12882 final void performAppGcLocked(ProcessRecord app) {
12883 try {
12884 app.lastRequestedGc = SystemClock.uptimeMillis();
12885 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012886 if (app.reportLowMemory) {
12887 app.reportLowMemory = false;
12888 app.thread.scheduleLowMemory();
12889 } else {
12890 app.thread.processInBackground();
12891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012892 }
12893 } catch (Exception e) {
12894 // whatever.
12895 }
12896 }
12897
12898 /**
12899 * Returns true if things are idle enough to perform GCs.
12900 */
Josh Bartel7f208742010-02-25 11:01:44 -060012901 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080012902 boolean processingBroadcasts = false;
12903 for (BroadcastQueue q : mBroadcastQueues) {
12904 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
12905 processingBroadcasts = true;
12906 }
12907 }
12908 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012909 && (mSleeping || (mMainStack.mResumedActivity != null &&
12910 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012911 }
12912
12913 /**
12914 * Perform GCs on all processes that are waiting for it, but only
12915 * if things are idle.
12916 */
12917 final void performAppGcsLocked() {
12918 final int N = mProcessesToGc.size();
12919 if (N <= 0) {
12920 return;
12921 }
Josh Bartel7f208742010-02-25 11:01:44 -060012922 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012923 while (mProcessesToGc.size() > 0) {
12924 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012925 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012926 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
12927 <= SystemClock.uptimeMillis()) {
12928 // To avoid spamming the system, we will GC processes one
12929 // at a time, waiting a few seconds between each.
12930 performAppGcLocked(proc);
12931 scheduleAppGcsLocked();
12932 return;
12933 } else {
12934 // It hasn't been long enough since we last GCed this
12935 // process... put it in the list to wait for its time.
12936 addProcessToGcListLocked(proc);
12937 break;
12938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012939 }
12940 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012941
12942 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012943 }
12944 }
12945
12946 /**
12947 * If all looks good, perform GCs on all processes waiting for them.
12948 */
12949 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060012950 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012951 performAppGcsLocked();
12952 return;
12953 }
12954 // Still not idle, wait some more.
12955 scheduleAppGcsLocked();
12956 }
12957
12958 /**
12959 * Schedule the execution of all pending app GCs.
12960 */
12961 final void scheduleAppGcsLocked() {
12962 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012963
12964 if (mProcessesToGc.size() > 0) {
12965 // Schedule a GC for the time to the next process.
12966 ProcessRecord proc = mProcessesToGc.get(0);
12967 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
12968
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012969 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012970 long now = SystemClock.uptimeMillis();
12971 if (when < (now+GC_TIMEOUT)) {
12972 when = now + GC_TIMEOUT;
12973 }
12974 mHandler.sendMessageAtTime(msg, when);
12975 }
12976 }
12977
12978 /**
12979 * Add a process to the array of processes waiting to be GCed. Keeps the
12980 * list in sorted order by the last GC time. The process can't already be
12981 * on the list.
12982 */
12983 final void addProcessToGcListLocked(ProcessRecord proc) {
12984 boolean added = false;
12985 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
12986 if (mProcessesToGc.get(i).lastRequestedGc <
12987 proc.lastRequestedGc) {
12988 added = true;
12989 mProcessesToGc.add(i+1, proc);
12990 break;
12991 }
12992 }
12993 if (!added) {
12994 mProcessesToGc.add(0, proc);
12995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012996 }
12997
12998 /**
12999 * Set up to ask a process to GC itself. This will either do it
13000 * immediately, or put it on the list of processes to gc the next
13001 * time things are idle.
13002 */
13003 final void scheduleAppGcLocked(ProcessRecord app) {
13004 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013005 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013006 return;
13007 }
13008 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070013009 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013010 scheduleAppGcsLocked();
13011 }
13012 }
13013
Dianne Hackborn287952c2010-09-22 22:34:31 -070013014 final void checkExcessivePowerUsageLocked(boolean doKills) {
13015 updateCpuStatsNow();
13016
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013017 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013018 boolean doWakeKills = doKills;
13019 boolean doCpuKills = doKills;
13020 if (mLastPowerCheckRealtime == 0) {
13021 doWakeKills = false;
13022 }
13023 if (mLastPowerCheckUptime == 0) {
13024 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013025 }
13026 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013027 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013028 }
13029 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013030 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13031 final long curUptime = SystemClock.uptimeMillis();
13032 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13033 mLastPowerCheckRealtime = curRealtime;
13034 mLastPowerCheckUptime = curUptime;
13035 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13036 doWakeKills = false;
13037 }
13038 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13039 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013040 }
13041 int i = mLruProcesses.size();
13042 while (i > 0) {
13043 i--;
13044 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013045 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013046 long wtime;
13047 synchronized (stats) {
13048 wtime = stats.getProcessWakeTime(app.info.uid,
13049 app.pid, curRealtime);
13050 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013051 long wtimeUsed = wtime - app.lastWakeTime;
13052 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13053 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013054 StringBuilder sb = new StringBuilder(128);
13055 sb.append("Wake for ");
13056 app.toShortString(sb);
13057 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013058 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013059 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013060 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013061 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013062 sb.append((wtimeUsed*100)/realtimeSince);
13063 sb.append("%)");
13064 Slog.i(TAG, sb.toString());
13065 sb.setLength(0);
13066 sb.append("CPU for ");
13067 app.toShortString(sb);
13068 sb.append(": over ");
13069 TimeUtils.formatDuration(uptimeSince, sb);
13070 sb.append(" used ");
13071 TimeUtils.formatDuration(cputimeUsed, sb);
13072 sb.append(" (");
13073 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013074 sb.append("%)");
13075 Slog.i(TAG, sb.toString());
13076 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013077 // If a process has held a wake lock for more
13078 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013079 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013080 if (doWakeKills && realtimeSince > 0
13081 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13082 synchronized (stats) {
13083 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13084 realtimeSince, wtimeUsed);
13085 }
13086 Slog.w(TAG, "Excessive wake lock in " + app.processName
13087 + " (pid " + app.pid + "): held " + wtimeUsed
13088 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013089 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13090 app.processName, app.setAdj, "excessive wake lock");
13091 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013092 } else if (doCpuKills && uptimeSince > 0
13093 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13094 synchronized (stats) {
13095 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13096 uptimeSince, cputimeUsed);
13097 }
13098 Slog.w(TAG, "Excessive CPU in " + app.processName
13099 + " (pid " + app.pid + "): used " + cputimeUsed
13100 + " during " + uptimeSince);
13101 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13102 app.processName, app.setAdj, "excessive cpu");
13103 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013104 } else {
13105 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013106 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013107 }
13108 }
13109 }
13110 }
13111
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013112 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
13113 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013114 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013115 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013116
13117 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013118 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013119 }
13120
Dianne Hackborn287952c2010-09-22 22:34:31 -070013121 final boolean wasKeeping = app.keeping;
13122
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013123 boolean success = true;
13124
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013125 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013126
Jeff Brown10e89712011-07-08 18:52:57 -070013127 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013128 if (wasKeeping && !app.keeping) {
13129 // This app is no longer something we want to keep. Note
13130 // its current wake lock time to later know to kill it if
13131 // it is not behaving well.
13132 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13133 synchronized (stats) {
13134 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13135 app.pid, SystemClock.elapsedRealtime());
13136 }
13137 app.lastCpuTime = app.curCpuTime;
13138 }
13139
13140 app.setRawAdj = app.curRawAdj;
13141 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013142
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013143 if (app.curAdj != app.setAdj) {
13144 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013145 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013146 TAG, "Set " + app.pid + " " + app.processName +
13147 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013148 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013149 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013150 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013151 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013152 }
13153 }
13154 if (app.setSchedGroup != app.curSchedGroup) {
13155 app.setSchedGroup = app.curSchedGroup;
13156 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13157 "Setting process group of " + app.processName
13158 + " to " + app.curSchedGroup);
13159 if (app.waitingToKill != null &&
13160 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13161 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13162 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13163 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013164 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013165 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013166 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013167 } else {
13168 if (true) {
13169 long oldId = Binder.clearCallingIdentity();
13170 try {
13171 Process.setProcessGroup(app.pid, app.curSchedGroup);
13172 } catch (Exception e) {
13173 Slog.w(TAG, "Failed setting process group of " + app.pid
13174 + " to " + app.curSchedGroup);
13175 e.printStackTrace();
13176 } finally {
13177 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013178 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013179 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013180 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013181 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013182 app.thread.setSchedulingGroup(app.curSchedGroup);
13183 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013184 }
13185 }
13186 }
13187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013188 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013189 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013190 }
13191
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013192 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013193 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013194 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013195 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013196 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013197 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013198 }
13199 }
13200 return resumedActivity;
13201 }
13202
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013203 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013204 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013205 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13206 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013207 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13208 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013209
13210 mAdjSeq++;
13211
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013212 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
13213 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013214 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13215 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013216 if (nowHidden != wasHidden) {
13217 // Changed to/from hidden state, so apps after it in the LRU
13218 // list may also be changed.
13219 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013220 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013221 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013222 }
13223
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013224 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013225 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013226 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13227
13228 if (false) {
13229 RuntimeException e = new RuntimeException();
13230 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013231 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013232 }
13233
13234 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013235 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013236
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013237 // Let's determine how many processes we have running vs.
13238 // how many slots we have for background processes; we may want
13239 // to put multiple processes in a slot of there are enough of
13240 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013241 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13242 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
13243 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
13244 if (emptyFactor < 1) emptyFactor = 1;
13245 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13246 if (hiddenFactor < 1) hiddenFactor = 1;
13247 int stepHidden = 0;
13248 int stepEmpty = 0;
13249 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
13250 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013251 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013252 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013253 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013254
13255 mNumNonHiddenProcs = 0;
13256 mNumHiddenProcs = 0;
13257
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013258 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013259 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013260 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013261 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013262 int nextHiddenAdj = curHiddenAdj+1;
13263 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13264 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013265 while (i > 0) {
13266 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013267 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013268 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013269 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013270 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013271 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13272 // This process was assigned as a hidden process... step the
13273 // hidden level.
13274 mNumHiddenProcs++;
13275 if (curHiddenAdj != nextHiddenAdj) {
13276 stepHidden++;
13277 if (stepHidden >= hiddenFactor) {
13278 stepHidden = 0;
13279 curHiddenAdj = nextHiddenAdj;
13280 nextHiddenAdj += 2;
13281 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13282 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13283 }
13284 }
13285 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013286 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013287 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013288 Slog.i(TAG, "No longer want " + app.processName
13289 + " (pid " + app.pid + "): hidden #" + numHidden);
13290 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13291 app.processName, app.setAdj, "too many background");
13292 app.killedBackground = true;
13293 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013294 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013295 } else {
13296 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13297 // This process was assigned as an empty process... step the
13298 // empty level.
13299 if (curEmptyAdj != nextEmptyAdj) {
13300 stepEmpty++;
13301 if (stepEmpty >= emptyFactor) {
13302 stepEmpty = 0;
13303 curEmptyAdj = nextEmptyAdj;
13304 nextEmptyAdj += 2;
13305 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13306 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13307 }
13308 }
13309 }
13310 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13311 mNumNonHiddenProcs++;
13312 }
13313 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13314 numEmpty++;
13315 if (numEmpty > emptyProcessLimit) {
13316 Slog.i(TAG, "No longer want " + app.processName
13317 + " (pid " + app.pid + "): empty #" + numEmpty);
13318 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13319 app.processName, app.setAdj, "too many background");
13320 app.killedBackground = true;
13321 Process.killProcessQuiet(app.pid);
13322 }
13323 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013324 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013325 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013326 // If this is an isolated process, and there are no
13327 // services running in it, then the process is no longer
13328 // needed. We agressively kill these because we can by
13329 // definition not re-use the same process again, and it is
13330 // good to avoid having whatever code was running in them
13331 // left sitting around after no longer needed.
13332 Slog.i(TAG, "Isolated process " + app.processName
13333 + " (pid " + app.pid + ") no longer needed");
13334 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13335 app.processName, app.setAdj, "isolated not needed");
13336 app.killedBackground = true;
13337 Process.killProcessQuiet(app.pid);
13338 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013339 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13340 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13341 && !app.killedBackground) {
13342 numTrimming++;
13343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013344 }
13345 }
13346
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013347 mNumServiceProcs = mNewNumServiceProcs;
13348
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013349 // Now determine the memory trimming level of background processes.
13350 // Unfortunately we need to start at the back of the list to do this
13351 // properly. We only do this if the number of background apps we
13352 // are managing to keep around is less than half the maximum we desire;
13353 // if we are keeping a good number around, we'll let them use whatever
13354 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013355 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13356 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13357 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013358 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013359 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013360 int minFactor = 2;
13361 if (mHomeProcess != null) minFactor++;
13362 if (mPreviousProcess != null) minFactor++;
13363 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013364 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013365 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013366 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013367 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013368 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013369 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13370 } else {
13371 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13372 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013373 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013374 for (i=0; i<N; i++) {
13375 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013376 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13377 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013378 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013379 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13380 try {
13381 app.thread.scheduleTrimMemory(curLevel);
13382 } catch (RemoteException e) {
13383 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013384 if (false) {
13385 // For now we won't do this; our memory trimming seems
13386 // to be good enough at this point that destroying
13387 // activities causes more harm than good.
13388 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13389 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013390 // Need to do this on its own message because the stack may not
13391 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013392 // For these apps we will also finish their activities
13393 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013394 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013395 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013396 }
13397 }
13398 app.trimMemoryLevel = curLevel;
13399 step++;
13400 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013401 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013402 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013403 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13404 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013405 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013406 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13407 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013408 break;
13409 }
13410 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013411 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013412 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013413 && app.thread != null) {
13414 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013415 app.thread.scheduleTrimMemory(
13416 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013417 } catch (RemoteException e) {
13418 }
13419 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013420 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013421 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013422 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013423 && app.pendingUiClean) {
13424 // If this application is now in the background and it
13425 // had done UI, then give it the special trim level to
13426 // have it free UI resources.
13427 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13428 if (app.trimMemoryLevel < level && app.thread != null) {
13429 try {
13430 app.thread.scheduleTrimMemory(level);
13431 } catch (RemoteException e) {
13432 }
13433 }
13434 app.pendingUiClean = false;
13435 }
13436 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013437 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013438 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013439 } catch (RemoteException e) {
13440 }
13441 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013442 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013443 }
13444 }
13445 } else {
13446 final int N = mLruProcesses.size();
13447 for (i=0; i<N; i++) {
13448 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013449 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013450 && app.pendingUiClean) {
13451 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13452 && app.thread != null) {
13453 try {
13454 app.thread.scheduleTrimMemory(
13455 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13456 } catch (RemoteException e) {
13457 }
13458 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013459 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013460 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013461 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013462 }
13463 }
13464
13465 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013466 // Need to do this on its own message because the stack may not
13467 // be in a consistent state at this point.
13468 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013470 }
13471
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013472 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013473 synchronized (this) {
13474 int i;
13475
13476 // First remove any unused application processes whose package
13477 // has been removed.
13478 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13479 final ProcessRecord app = mRemovedProcesses.get(i);
13480 if (app.activities.size() == 0
13481 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013482 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013483 TAG, "Exiting empty application process "
13484 + app.processName + " ("
13485 + (app.thread != null ? app.thread.asBinder() : null)
13486 + ")\n");
13487 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013488 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13489 app.processName, app.setAdj, "empty");
13490 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013491 } else {
13492 try {
13493 app.thread.scheduleExit();
13494 } catch (Exception e) {
13495 // Ignore exceptions.
13496 }
13497 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013498 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013499 mRemovedProcesses.remove(i);
13500
13501 if (app.persistent) {
13502 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013503 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013504 }
13505 }
13506 }
13507 }
13508
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013509 // Now update the oom adj for all processes.
13510 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013511 }
13512 }
13513
13514 /** This method sends the specified signal to each of the persistent apps */
13515 public void signalPersistentProcesses(int sig) throws RemoteException {
13516 if (sig != Process.SIGNAL_USR1) {
13517 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13518 }
13519
13520 synchronized (this) {
13521 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13522 != PackageManager.PERMISSION_GRANTED) {
13523 throw new SecurityException("Requires permission "
13524 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13525 }
13526
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013527 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13528 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013529 if (r.thread != null && r.persistent) {
13530 Process.sendSignal(r.pid, sig);
13531 }
13532 }
13533 }
13534 }
13535
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013536 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13537 if (proc == null || proc == mProfileProc) {
13538 proc = mProfileProc;
13539 path = mProfileFile;
13540 profileType = mProfileType;
13541 clearProfilerLocked();
13542 }
13543 if (proc == null) {
13544 return;
13545 }
13546 try {
13547 proc.thread.profilerControl(false, path, null, profileType);
13548 } catch (RemoteException e) {
13549 throw new IllegalStateException("Process disappeared");
13550 }
13551 }
13552
13553 private void clearProfilerLocked() {
13554 if (mProfileFd != null) {
13555 try {
13556 mProfileFd.close();
13557 } catch (IOException e) {
13558 }
13559 }
13560 mProfileApp = null;
13561 mProfileProc = null;
13562 mProfileFile = null;
13563 mProfileType = 0;
13564 mAutoStopProfiler = false;
13565 }
13566
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013567 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013568 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013569
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013570 try {
13571 synchronized (this) {
13572 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13573 // its own permission.
13574 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13575 != PackageManager.PERMISSION_GRANTED) {
13576 throw new SecurityException("Requires permission "
13577 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013578 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013579
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013580 if (start && fd == null) {
13581 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013582 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013583
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013584 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013585 if (process != null) {
13586 try {
13587 int pid = Integer.parseInt(process);
13588 synchronized (mPidsSelfLocked) {
13589 proc = mPidsSelfLocked.get(pid);
13590 }
13591 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013592 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013593
13594 if (proc == null) {
13595 HashMap<String, SparseArray<ProcessRecord>> all
13596 = mProcessNames.getMap();
13597 SparseArray<ProcessRecord> procs = all.get(process);
13598 if (procs != null && procs.size() > 0) {
13599 proc = procs.valueAt(0);
13600 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013601 }
13602 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013603
13604 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013605 throw new IllegalArgumentException("Unknown process: " + process);
13606 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013607
13608 if (start) {
13609 stopProfilerLocked(null, null, 0);
13610 setProfileApp(proc.info, proc.processName, path, fd, false);
13611 mProfileProc = proc;
13612 mProfileType = profileType;
13613 try {
13614 fd = fd.dup();
13615 } catch (IOException e) {
13616 fd = null;
13617 }
13618 proc.thread.profilerControl(start, path, fd, profileType);
13619 fd = null;
13620 mProfileFd = null;
13621 } else {
13622 stopProfilerLocked(proc, path, profileType);
13623 if (fd != null) {
13624 try {
13625 fd.close();
13626 } catch (IOException e) {
13627 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013628 }
13629 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013630
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013631 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013632 }
13633 } catch (RemoteException e) {
13634 throw new IllegalStateException("Process disappeared");
13635 } finally {
13636 if (fd != null) {
13637 try {
13638 fd.close();
13639 } catch (IOException e) {
13640 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013641 }
13642 }
13643 }
Andy McFadden824c5102010-07-09 16:26:57 -070013644
13645 public boolean dumpHeap(String process, boolean managed,
13646 String path, ParcelFileDescriptor fd) throws RemoteException {
13647
13648 try {
13649 synchronized (this) {
13650 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13651 // its own permission (same as profileControl).
13652 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13653 != PackageManager.PERMISSION_GRANTED) {
13654 throw new SecurityException("Requires permission "
13655 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13656 }
13657
13658 if (fd == null) {
13659 throw new IllegalArgumentException("null fd");
13660 }
13661
13662 ProcessRecord proc = null;
13663 try {
13664 int pid = Integer.parseInt(process);
13665 synchronized (mPidsSelfLocked) {
13666 proc = mPidsSelfLocked.get(pid);
13667 }
13668 } catch (NumberFormatException e) {
13669 }
13670
13671 if (proc == null) {
13672 HashMap<String, SparseArray<ProcessRecord>> all
13673 = mProcessNames.getMap();
13674 SparseArray<ProcessRecord> procs = all.get(process);
13675 if (procs != null && procs.size() > 0) {
13676 proc = procs.valueAt(0);
13677 }
13678 }
13679
13680 if (proc == null || proc.thread == null) {
13681 throw new IllegalArgumentException("Unknown process: " + process);
13682 }
13683
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013684 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13685 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013686 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13687 throw new SecurityException("Process not debuggable: " + proc);
13688 }
13689 }
13690
13691 proc.thread.dumpHeap(managed, path, fd);
13692 fd = null;
13693 return true;
13694 }
13695 } catch (RemoteException e) {
13696 throw new IllegalStateException("Process disappeared");
13697 } finally {
13698 if (fd != null) {
13699 try {
13700 fd.close();
13701 } catch (IOException e) {
13702 }
13703 }
13704 }
13705 }
13706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013707 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13708 public void monitor() {
13709 synchronized (this) { }
13710 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013711
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013712 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013713 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13714 ProcessRecord processRecord = mLruProcesses.get(i);
13715 try {
13716 if (processRecord.thread != null) {
13717 processRecord.thread.setCoreSettings(settings);
13718 }
13719 } catch (RemoteException re) {
13720 /* ignore */
13721 }
13722 }
13723 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013724
13725 // Multi-user methods
13726
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013727 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070013728 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013729 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13730 != PackageManager.PERMISSION_GRANTED) {
13731 String msg = "Permission Denial: switchUser() from pid="
13732 + Binder.getCallingPid()
13733 + ", uid=" + Binder.getCallingUid()
13734 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13735 Slog.w(TAG, msg);
13736 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013737 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013738 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013739 if (mCurrentUserId == userId) {
13740 return true;
13741 }
13742
13743 // If the user we are switching to is not currently started, then
13744 // we need to start it now.
13745 if (mStartedUsers.get(userId) == null) {
13746 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Amith Yamasani742a6712011-05-04 14:49:28 -070013747 }
13748
13749 mCurrentUserId = userId;
13750 boolean haveActivities = mMainStack.switchUser(userId);
13751 if (!haveActivities) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013752 startHomeActivityLocked(userId, mStartedUsers.get(userId));
Amith Yamasani742a6712011-05-04 14:49:28 -070013753 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013754 }
Amith Yamasani13593602012-03-22 16:16:17 -070013755
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013756 long ident = Binder.clearCallingIdentity();
13757 try {
13758 // Inform of user switch
13759 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
13760 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070013761 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
13762 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013763 } finally {
13764 Binder.restoreCallingIdentity(ident);
13765 }
Amith Yamasani13593602012-03-22 16:16:17 -070013766
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013767 return true;
13768 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013769
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013770 void finishUserSwitch(UserStartedState uss) {
13771 synchronized (this) {
13772 if (uss.mState == UserStartedState.STATE_BOOTING
13773 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
13774 uss.mState = UserStartedState.STATE_RUNNING;
Dianne Hackborn41203752012-08-31 14:05:51 -070013775 final int userId = uss.mHandle.getIdentifier();
13776 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
13777 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
13778 broadcastIntentLocked(null, null, intent,
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013779 null, null, 0, null, null,
13780 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
Dianne Hackborn41203752012-08-31 14:05:51 -070013781 false, false, MY_PID, Process.SYSTEM_UID, userId);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013782 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013783 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013784 }
13785
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013786 @Override
13787 public int stopUser(final int userId, final IStopUserCallback callback) {
13788 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13789 != PackageManager.PERMISSION_GRANTED) {
13790 String msg = "Permission Denial: switchUser() from pid="
13791 + Binder.getCallingPid()
13792 + ", uid=" + Binder.getCallingUid()
13793 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13794 Slog.w(TAG, msg);
13795 throw new SecurityException(msg);
13796 }
13797 if (userId <= 0) {
13798 throw new IllegalArgumentException("Can't stop primary user " + userId);
13799 }
Amith Yamasani13593602012-03-22 16:16:17 -070013800 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013801 if (mCurrentUserId == userId) {
13802 return ActivityManager.USER_OP_IS_CURRENT;
13803 }
13804
13805 final UserStartedState uss = mStartedUsers.get(userId);
13806 if (uss == null) {
13807 // User is not started, nothing to do... but we do need to
13808 // callback if requested.
13809 if (callback != null) {
13810 mHandler.post(new Runnable() {
13811 @Override
13812 public void run() {
13813 try {
13814 callback.userStopped(userId);
13815 } catch (RemoteException e) {
13816 }
13817 }
13818 });
13819 }
13820 return ActivityManager.USER_OP_SUCCESS;
13821 }
13822
13823 if (callback != null) {
13824 uss.mStopCallbacks.add(callback);
13825 }
13826
13827 if (uss.mState != UserStartedState.STATE_STOPPING) {
13828 uss.mState = UserStartedState.STATE_STOPPING;
13829
13830 long ident = Binder.clearCallingIdentity();
13831 try {
13832 // Inform of user switch
13833 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
13834 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
13835 @Override
13836 public void performReceive(Intent intent, int resultCode, String data,
13837 Bundle extras, boolean ordered, boolean sticky) {
13838 finishUserStop(uss);
13839 }
13840 };
13841 broadcastIntentLocked(null, null, intent,
13842 null, resultReceiver, 0, null, null, null,
13843 true, false, MY_PID, Process.SYSTEM_UID, userId);
13844 } finally {
13845 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070013846 }
13847 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013848 }
Amith Yamasani13593602012-03-22 16:16:17 -070013849
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013850 return ActivityManager.USER_OP_SUCCESS;
13851 }
13852
13853 void finishUserStop(UserStartedState uss) {
13854 final int userId = uss.mHandle.getIdentifier();
13855 boolean stopped;
13856 ArrayList<IStopUserCallback> callbacks;
13857 synchronized (this) {
13858 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
13859 if (uss.mState != UserStartedState.STATE_STOPPING
13860 || mStartedUsers.get(userId) != uss) {
13861 stopped = false;
13862 } else {
13863 stopped = true;
13864 // User can no longer run.
13865 mStartedUsers.remove(userId);
13866
13867 // Clean up all state and processes associated with the user.
13868 // Kill all the processes for the user.
13869 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070013870 }
13871 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013872
13873 for (int i=0; i<callbacks.size(); i++) {
13874 try {
13875 if (stopped) callbacks.get(i).userStopped(userId);
13876 else callbacks.get(i).userStopAborted(userId);
13877 } catch (RemoteException e) {
13878 }
13879 }
13880 }
13881
13882 @Override
13883 public UserInfo getCurrentUser() {
13884 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13885 != PackageManager.PERMISSION_GRANTED) {
13886 String msg = "Permission Denial: getCurrentUser() from pid="
13887 + Binder.getCallingPid()
13888 + ", uid=" + Binder.getCallingUid()
13889 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13890 Slog.w(TAG, msg);
13891 throw new SecurityException(msg);
13892 }
13893 synchronized (this) {
13894 return getUserManager().getUserInfo(mCurrentUserId);
13895 }
Amith Yamasani13593602012-03-22 16:16:17 -070013896 }
13897
Amith Yamasani742a6712011-05-04 14:49:28 -070013898 private boolean userExists(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -070013899 UserInfo user = getUserManager().getUserInfo(userId);
13900 return user != null;
13901 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013902
Amith Yamasani258848d2012-08-10 17:06:33 -070013903 UserManager getUserManager() {
13904 if (mUserManager == null) {
13905 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
13906 }
13907 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070013908 }
13909
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013910 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013911 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013912
13913 throw new SecurityException("Caller uid=" + uid
13914 + " is not privileged to communicate with user=" + userId);
13915 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013916
13917 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013918 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070013919 }
13920
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013921 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080013922 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070013923 ApplicationInfo newInfo = new ApplicationInfo(info);
13924 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070013925 newInfo.dataDir = USER_DATA_DIR + userId + "/"
13926 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070013927 return newInfo;
13928 }
13929
13930 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070013931 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013932 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070013933 return aInfo;
13934 }
13935
13936 ActivityInfo info = new ActivityInfo(aInfo);
13937 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
13938 return info;
13939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013940}