blob: 6c87252dcb617be9220572ad2462bae7b416a152 [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),
1132 PendingIntent.getActivity(mContext, 0, root.intent,
1133 PendingIntent.FLAG_CANCEL_CURRENT));
1134
1135 try {
1136 int[] outId = new int[1];
1137 inm.enqueueNotification("android", R.string.heavy_weight_notification,
1138 notification, outId);
1139 } catch (RuntimeException e) {
1140 Slog.w(ActivityManagerService.TAG,
1141 "Error showing notification for heavy-weight app", e);
1142 } catch (RemoteException e) {
1143 }
1144 } catch (NameNotFoundException e) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07001145 Slog.w(TAG, "Unable to create context for heavy notification", e);
Dianne Hackborn860755f2010-06-03 18:47:52 -07001146 }
1147 } break;
1148 case CANCEL_HEAVY_NOTIFICATION_MSG: {
1149 INotificationManager inm = NotificationManager.getService();
1150 if (inm == null) {
1151 return;
1152 }
1153 try {
1154 inm.cancelNotification("android",
1155 R.string.heavy_weight_notification);
1156 } catch (RuntimeException e) {
1157 Slog.w(ActivityManagerService.TAG,
1158 "Error canceling notification for service", e);
1159 } catch (RemoteException e) {
1160 }
1161 } break;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001162 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: {
1163 synchronized (ActivityManagerService.this) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001164 checkExcessivePowerUsageLocked(true);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -07001165 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001166 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
1167 sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07001168 }
1169 } break;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001170 case SHOW_COMPAT_MODE_DIALOG_MSG: {
1171 synchronized (ActivityManagerService.this) {
1172 ActivityRecord ar = (ActivityRecord)msg.obj;
1173 if (mCompatModeDialog != null) {
1174 if (mCompatModeDialog.mAppInfo.packageName.equals(
1175 ar.info.applicationInfo.packageName)) {
1176 return;
1177 }
1178 mCompatModeDialog.dismiss();
1179 mCompatModeDialog = null;
1180 }
Dianne Hackborn29478262011-06-07 15:44:22 -07001181 if (ar != null && false) {
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001182 if (mCompatModePackages.getPackageAskCompatModeLocked(
1183 ar.packageName)) {
1184 int mode = mCompatModePackages.computeCompatModeLocked(
1185 ar.info.applicationInfo);
1186 if (mode == ActivityManager.COMPAT_MODE_DISABLED
1187 || mode == ActivityManager.COMPAT_MODE_ENABLED) {
1188 mCompatModeDialog = new CompatModeDialog(
1189 ActivityManagerService.this, mContext,
1190 ar.info.applicationInfo);
1191 mCompatModeDialog.show();
1192 }
1193 }
1194 }
1195 }
Dianne Hackborn36f80f32011-05-31 18:26:45 -07001196 break;
1197 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -07001198 case DISPATCH_PROCESSES_CHANGED: {
1199 dispatchProcessesChanged();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001200 break;
1201 }
1202 case DISPATCH_PROCESS_DIED: {
Jeff Sharkey287bd832011-05-28 19:36:26 -07001203 final int pid = msg.arg1;
1204 final int uid = msg.arg2;
1205 dispatchProcessDied(pid, uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001206 break;
1207 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001208 case REPORT_MEM_USAGE: {
1209 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
1210 if (!isDebuggable) {
1211 return;
1212 }
1213 synchronized (ActivityManagerService.this) {
1214 long now = SystemClock.uptimeMillis();
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001215 if (now < (mLastMemUsageReportTime+5*60*1000)) {
1216 // Don't report more than every 5 minutes to somewhat
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001217 // avoid spamming.
1218 return;
1219 }
1220 mLastMemUsageReportTime = now;
1221 }
1222 Thread thread = new Thread() {
1223 @Override public void run() {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001224 StringBuilder dropBuilder = new StringBuilder(1024);
1225 StringBuilder logBuilder = new StringBuilder(1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -08001226 StringWriter oomSw = new StringWriter();
1227 PrintWriter oomPw = new PrintWriter(oomSw);
1228 StringWriter catSw = new StringWriter();
1229 PrintWriter catPw = new PrintWriter(catSw);
1230 String[] emptyArgs = new String[] { };
1231 StringBuilder tag = new StringBuilder(128);
1232 StringBuilder stack = new StringBuilder(128);
1233 tag.append("Low on memory -- ");
1234 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw,
1235 tag, stack);
1236 dropBuilder.append(stack);
1237 dropBuilder.append('\n');
1238 dropBuilder.append('\n');
1239 String oomString = oomSw.toString();
1240 dropBuilder.append(oomString);
1241 dropBuilder.append('\n');
1242 logBuilder.append(oomString);
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001243 try {
1244 java.lang.Process proc = Runtime.getRuntime().exec(new String[] {
1245 "procrank", });
1246 final InputStreamReader converter = new InputStreamReader(
1247 proc.getInputStream());
1248 BufferedReader in = new BufferedReader(converter);
1249 String line;
1250 while (true) {
1251 line = in.readLine();
1252 if (line == null) {
1253 break;
1254 }
1255 if (line.length() > 0) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001256 logBuilder.append(line);
1257 logBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001258 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001259 dropBuilder.append(line);
1260 dropBuilder.append('\n');
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001261 }
1262 converter.close();
1263 } catch (IOException e) {
1264 }
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001265 synchronized (ActivityManagerService.this) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08001266 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001267 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001268 catPw.println();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001269 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0,
1270 false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001271 catPw.println();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001272 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null);
Dianne Hackborn7aa6d312011-11-15 15:01:14 -08001273 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001274 dropBuilder.append(catSw.toString());
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001275 addErrorToDropBox("lowmem", null, "system_server", null,
1276 null, tag.toString(), dropBuilder.toString(), null, null);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08001277 Slog.i(TAG, logBuilder.toString());
Dianne Hackborn04d6db32011-11-04 20:07:24 -07001278 synchronized (ActivityManagerService.this) {
1279 long now = SystemClock.uptimeMillis();
1280 if (mLastMemUsageReportTime < now) {
1281 mLastMemUsageReportTime = now;
1282 }
1283 }
1284 }
1285 };
1286 thread.start();
1287 break;
1288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 }
1290 }
1291 };
1292
1293 public static void setSystemProcess() {
1294 try {
1295 ActivityManagerService m = mSelf;
1296
Dianne Hackborna573f6a2012-02-09 16:12:18 -08001297 ServiceManager.addService("activity", m, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 ServiceManager.addService("meminfo", new MemBinder(m));
Chet Haase9c1e23b2011-03-24 10:51:31 -07001299 ServiceManager.addService("gfxinfo", new GraphicsBinder(m));
Jeff Brown6754ba22011-12-14 20:20:01 -08001300 ServiceManager.addService("dbinfo", new DbBinder(m));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 if (MONITOR_CPU_USAGE) {
1302 ServiceManager.addService("cpuinfo", new CpuBinder(m));
1303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 ServiceManager.addService("permission", new PermissionController(m));
1305
1306 ApplicationInfo info =
1307 mSelf.mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001308 "android", STOCK_PM_FLAGS);
Mike Cleron432b7132009-09-24 15:28:29 -07001309 mSystemThread.installSystemApplicationInfo(info);
1310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 synchronized (mSelf) {
1312 ProcessRecord app = mSelf.newProcessRecordLocked(
1313 mSystemThread.getApplicationThread(), info,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001314 info.processName, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 app.persistent = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08001316 app.pid = MY_PID;
Dianne Hackborn7d608422011-08-07 16:24:18 -07001317 app.maxAdj = ProcessList.SYSTEM_ADJ;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001318 mSelf.mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 synchronized (mSelf.mPidsSelfLocked) {
1320 mSelf.mPidsSelfLocked.put(app.pid, app);
1321 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001322 mSelf.updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 }
1324 } catch (PackageManager.NameNotFoundException e) {
1325 throw new RuntimeException(
1326 "Unable to find android system package", e);
1327 }
1328 }
1329
1330 public void setWindowManager(WindowManagerService wm) {
1331 mWindowManager = wm;
1332 }
1333
1334 public static final Context main(int factoryTest) {
1335 AThread thr = new AThread();
1336 thr.start();
1337
1338 synchronized (thr) {
1339 while (thr.mService == null) {
1340 try {
1341 thr.wait();
1342 } catch (InterruptedException e) {
1343 }
1344 }
1345 }
1346
1347 ActivityManagerService m = thr.mService;
1348 mSelf = m;
1349 ActivityThread at = ActivityThread.systemMain();
1350 mSystemThread = at;
1351 Context context = at.getSystemContext();
Dianne Hackborn247fe742011-01-08 17:25:57 -08001352 context.setTheme(android.R.style.Theme_Holo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 m.mContext = context;
1354 m.mFactoryTest = factoryTest;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001355 m.mMainStack = new ActivityStack(m, context, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356
1357 m.mBatteryStatsService.publish(context);
1358 m.mUsageStatsService.publish(context);
1359
1360 synchronized (thr) {
1361 thr.mReady = true;
1362 thr.notifyAll();
1363 }
1364
1365 m.startRunning(null, null, null, null);
1366
1367 return context;
1368 }
1369
1370 public static ActivityManagerService self() {
1371 return mSelf;
1372 }
1373
1374 static class AThread extends Thread {
1375 ActivityManagerService mService;
1376 boolean mReady = false;
1377
1378 public AThread() {
1379 super("ActivityManager");
1380 }
1381
1382 public void run() {
1383 Looper.prepare();
1384
1385 android.os.Process.setThreadPriority(
1386 android.os.Process.THREAD_PRIORITY_FOREGROUND);
Christopher Tate160edb32010-06-30 17:46:30 -07001387 android.os.Process.setCanSelfBackground(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388
1389 ActivityManagerService m = new ActivityManagerService();
1390
1391 synchronized (this) {
1392 mService = m;
1393 notifyAll();
1394 }
1395
1396 synchronized (this) {
1397 while (!mReady) {
1398 try {
1399 wait();
1400 } catch (InterruptedException e) {
1401 }
1402 }
1403 }
1404
Brad Fitzpatrickec062f62010-11-03 09:56:54 -07001405 // For debug builds, log event loop stalls to dropbox for analysis.
1406 if (StrictMode.conditionallyEnableDebugLogging()) {
1407 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper");
1408 }
1409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 Looper.loop();
1411 }
1412 }
1413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 static class MemBinder extends Binder {
1415 ActivityManagerService mActivityManagerService;
1416 MemBinder(ActivityManagerService activityManagerService) {
1417 mActivityManagerService = activityManagerService;
1418 }
1419
1420 @Override
1421 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001422 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1423 != PackageManager.PERMISSION_GRANTED) {
1424 pw.println("Permission Denial: can't dump meminfo from from pid="
1425 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1426 + " without permission " + android.Manifest.permission.DUMP);
1427 return;
1428 }
1429
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -08001430 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args,
Dianne Hackborn672342c2011-11-29 11:29:02 -08001431 false, null, null, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 }
1433 }
1434
Chet Haase9c1e23b2011-03-24 10:51:31 -07001435 static class GraphicsBinder extends Binder {
1436 ActivityManagerService mActivityManagerService;
1437 GraphicsBinder(ActivityManagerService activityManagerService) {
1438 mActivityManagerService = activityManagerService;
1439 }
1440
1441 @Override
1442 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001443 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1444 != PackageManager.PERMISSION_GRANTED) {
1445 pw.println("Permission Denial: can't dump gfxinfo from from pid="
1446 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1447 + " without permission " + android.Manifest.permission.DUMP);
1448 return;
1449 }
1450
Dianne Hackborne17aeb32011-04-07 15:11:57 -07001451 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args);
Chet Haase9c1e23b2011-03-24 10:51:31 -07001452 }
1453 }
1454
Jeff Brown6754ba22011-12-14 20:20:01 -08001455 static class DbBinder extends Binder {
1456 ActivityManagerService mActivityManagerService;
1457 DbBinder(ActivityManagerService activityManagerService) {
1458 mActivityManagerService = activityManagerService;
1459 }
1460
1461 @Override
1462 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
1463 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1464 != PackageManager.PERMISSION_GRANTED) {
1465 pw.println("Permission Denial: can't dump dbinfo from from pid="
1466 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1467 + " without permission " + android.Manifest.permission.DUMP);
1468 return;
1469 }
1470
1471 mActivityManagerService.dumpDbInfo(fd, pw, args);
1472 }
1473 }
1474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 static class CpuBinder extends Binder {
1476 ActivityManagerService mActivityManagerService;
1477 CpuBinder(ActivityManagerService activityManagerService) {
1478 mActivityManagerService = activityManagerService;
1479 }
1480
1481 @Override
1482 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Kenny Root3abd75b2011-09-29 11:00:41 -07001483 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP)
1484 != PackageManager.PERMISSION_GRANTED) {
1485 pw.println("Permission Denial: can't dump cpuinfo from from pid="
1486 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid()
1487 + " without permission " + android.Manifest.permission.DUMP);
1488 return;
1489 }
1490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 synchronized (mActivityManagerService.mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07001492 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad());
1493 pw.print(mActivityManagerService.mProcessStats.printCurrentState(
1494 SystemClock.uptimeMillis()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
1496 }
1497 }
1498
1499 private ActivityManagerService() {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001500 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
Dianne Hackborn2c6c5e62009-10-08 17:55:49 -07001501
Dianne Hackborn40c8db52012-02-10 18:59:48 -08001502 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT);
1503 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT);
1504 mBroadcastQueues[0] = mFgBroadcastQueue;
1505 mBroadcastQueues[1] = mBgBroadcastQueue;
1506
Dianne Hackborn599db5c2012-08-03 19:28:48 -07001507 mServices = new ActiveServices(this);
1508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001509 File dataDir = Environment.getDataDirectory();
1510 File systemDir = new File(dataDir, "system");
1511 systemDir.mkdirs();
1512 mBatteryStatsService = new BatteryStatsService(new File(
1513 systemDir, "batterystats.bin").toString());
1514 mBatteryStatsService.getActiveStatistics().readLocked();
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001515 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
Dianne Hackborn287952c2010-09-22 22:34:31 -07001516 mOnBattery = DEBUG_POWER ? true
1517 : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001518 mBatteryStatsService.getActiveStatistics().setCallback(this);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001520 mUsageStatsService = new UsageStatsService(new File(
Dianne Hackborn6447ca32009-04-07 19:50:08 -07001521 systemDir, "usagestats").toString());
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001522 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001524 // User 0 is the first and only user that runs at boot.
1525 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true));
1526
Jack Palevichb90d28c2009-07-22 15:35:24 -07001527 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
1528 ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
1529
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08001530 mConfiguration.setToDefaults();
1531 mConfiguration.locale = Locale.getDefault();
Dianne Hackborn813075a62011-11-14 17:45:19 -08001532 mConfigurationSeq = mConfiguration.seq = 1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 mProcessStats.init();
1534
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07001535 mCompatModePackages = new CompatModePackages(this, systemDir);
1536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 // Add ourself to the Watchdog monitors.
1538 Watchdog.getInstance().addMonitor(this);
1539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 mProcessStatsThread = new Thread("ProcessStats") {
1541 public void run() {
1542 while (true) {
1543 try {
1544 try {
1545 synchronized(this) {
1546 final long now = SystemClock.uptimeMillis();
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001547 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001549 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 // + ", write delay=" + nextWriteDelay);
1551 if (nextWriteDelay < nextCpuDelay) {
1552 nextCpuDelay = nextWriteDelay;
1553 }
1554 if (nextCpuDelay > 0) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001555 mProcessStatsMutexFree.set(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 this.wait(nextCpuDelay);
1557 }
1558 }
1559 } catch (InterruptedException e) {
1560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 updateCpuStatsNow();
1562 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001563 Slog.e(TAG, "Unexpected exception collecting process stats", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
1565 }
1566 }
1567 };
1568 mProcessStatsThread.start();
1569 }
1570
1571 @Override
1572 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1573 throws RemoteException {
Dianne Hackborna53de062012-05-08 18:53:51 -07001574 if (code == SYSPROPS_TRANSACTION) {
1575 // We need to tell all apps about the system property change.
1576 ArrayList<IBinder> procs = new ArrayList<IBinder>();
1577 synchronized(this) {
1578 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
1579 final int NA = apps.size();
1580 for (int ia=0; ia<NA; ia++) {
1581 ProcessRecord app = apps.valueAt(ia);
1582 if (app.thread != null) {
1583 procs.add(app.thread.asBinder());
1584 }
1585 }
1586 }
1587 }
1588
1589 int N = procs.size();
1590 for (int i=0; i<N; i++) {
1591 Parcel data2 = Parcel.obtain();
1592 try {
1593 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0);
1594 } catch (RemoteException e) {
1595 }
1596 data2.recycle();
1597 }
1598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 try {
1600 return super.onTransact(code, data, reply, flags);
1601 } catch (RuntimeException e) {
1602 // The activity manager only throws security exceptions, so let's
1603 // log all others.
1604 if (!(e instanceof SecurityException)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001605 Slog.e(TAG, "Activity Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 }
1607 throw e;
1608 }
1609 }
1610
1611 void updateCpuStats() {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001612 final long now = SystemClock.uptimeMillis();
1613 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) {
1614 return;
1615 }
1616 if (mProcessStatsMutexFree.compareAndSet(true, false)) {
1617 synchronized (mProcessStatsThread) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 mProcessStatsThread.notify();
1619 }
1620 }
1621 }
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001622
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 void updateCpuStatsNow() {
1624 synchronized (mProcessStatsThread) {
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001625 mProcessStatsMutexFree.set(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 final long now = SystemClock.uptimeMillis();
1627 boolean haveNewCpuStats = false;
Amith Yamasanieaeb6632009-06-03 15:16:10 -07001628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 if (MONITOR_CPU_USAGE &&
Brad Fitzpatrick01fad4a2010-04-19 10:47:40 -07001630 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) {
1631 mLastCpuTime.set(now);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 haveNewCpuStats = true;
1633 mProcessStats.update();
Joe Onorato8a9b2202010-02-26 18:56:32 -08001634 //Slog.i(TAG, mProcessStats.printCurrentState());
1635 //Slog.i(TAG, "Total CPU usage: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 // + mProcessStats.getTotalCpuPercent() + "%");
1637
Joe Onorato8a9b2202010-02-26 18:56:32 -08001638 // Slog the cpu usage if the property is set.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 if ("true".equals(SystemProperties.get("events.cpu"))) {
1640 int user = mProcessStats.getLastUserTime();
1641 int system = mProcessStats.getLastSystemTime();
1642 int iowait = mProcessStats.getLastIoWaitTime();
1643 int irq = mProcessStats.getLastIrqTime();
1644 int softIrq = mProcessStats.getLastSoftIrqTime();
1645 int idle = mProcessStats.getLastIdleTime();
1646
1647 int total = user + system + iowait + irq + softIrq + idle;
1648 if (total == 0) total = 1;
1649
Doug Zongker2bec3d42009-12-04 12:52:44 -08001650 EventLog.writeEvent(EventLogTags.CPU,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 ((user+system+iowait+irq+softIrq) * 100) / total,
1652 (user * 100) / total,
1653 (system * 100) / total,
1654 (iowait * 100) / total,
1655 (irq * 100) / total,
1656 (softIrq * 100) / total);
1657 }
1658 }
1659
Amith Yamasanie43530a2009-08-21 13:11:37 -07001660 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes();
Amith Yamasani819f9282009-06-24 23:18:15 -07001661 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics();
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001662 synchronized(bstats) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 synchronized(mPidsSelfLocked) {
1664 if (haveNewCpuStats) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001665 if (mOnBattery) {
1666 int perc = bstats.startAddingCpuLocked();
1667 int totalUTime = 0;
1668 int totalSTime = 0;
Dianne Hackborn287952c2010-09-22 22:34:31 -07001669 final int N = mProcessStats.countStats();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 for (int i=0; i<N; i++) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001671 ProcessStats.Stats st = mProcessStats.getStats(i);
1672 if (!st.working) {
1673 continue;
1674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001675 ProcessRecord pr = mPidsSelfLocked.get(st.pid);
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001676 int otherUTime = (st.rel_utime*perc)/100;
1677 int otherSTime = (st.rel_stime*perc)/100;
1678 totalUTime += otherUTime;
1679 totalSTime += otherSTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 if (pr != null) {
1681 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001682 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1683 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001684 ps.addSpeedStepTimes(cpuSpeedTimes);
Dianne Hackborn287952c2010-09-22 22:34:31 -07001685 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10;
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001686 } else {
1687 BatteryStatsImpl.Uid.Proc ps =
Amith Yamasani819f9282009-06-24 23:18:15 -07001688 bstats.getProcessStatsLocked(st.name, st.pid);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001689 if (ps != null) {
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001690 ps.addCpuTimeLocked(st.rel_utime-otherUTime,
1691 st.rel_stime-otherSTime);
Amith Yamasanie43530a2009-08-21 13:11:37 -07001692 ps.addSpeedStepTimes(cpuSpeedTimes);
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001693 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695 }
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001696 bstats.finishAddingCpuLocked(perc, totalUTime,
1697 totalSTime, cpuSpeedTimes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 }
1699 }
1700 }
Amith Yamasani32dbefd2009-06-19 09:21:17 -07001701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) {
1703 mLastWriteTime = now;
Dianne Hackbornce2ef762010-09-20 11:39:14 -07001704 mBatteryStatsService.getActiveStatistics().writeAsyncLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 }
1706 }
1707 }
1708 }
1709
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001710 @Override
1711 public void batteryNeedsCpuUpdate() {
1712 updateCpuStatsNow();
1713 }
1714
1715 @Override
1716 public void batteryPowerChanged(boolean onBattery) {
1717 // When plugging in, update the CPU stats first before changing
1718 // the plug state.
1719 updateCpuStatsNow();
1720 synchronized (this) {
1721 synchronized(mPidsSelfLocked) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07001722 mOnBattery = DEBUG_POWER ? true : onBattery;
Dianne Hackborn0d903a82010-09-07 23:51:03 -07001723 }
1724 }
1725 }
1726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001727 /**
1728 * Initialize the application bind args. These are passed to each
1729 * process when the bindApplication() IPC is sent to the process. They're
1730 * lazily setup to make sure the services are running when they're asked for.
1731 */
1732 private HashMap<String, IBinder> getCommonServicesLocked() {
1733 if (mAppBindArgs == null) {
1734 mAppBindArgs = new HashMap<String, IBinder>();
1735
1736 // Setup the application init args
1737 mAppBindArgs.put("package", ServiceManager.getService("package"));
1738 mAppBindArgs.put("window", ServiceManager.getService("window"));
1739 mAppBindArgs.put(Context.ALARM_SERVICE,
1740 ServiceManager.getService(Context.ALARM_SERVICE));
1741 }
1742 return mAppBindArgs;
1743 }
1744
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001745 final void setFocusedActivityLocked(ActivityRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 if (mFocusedActivity != r) {
1747 mFocusedActivity = r;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08001748 if (r != null) {
1749 mWindowManager.setFocusedApp(r.appToken, true);
1750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 }
1752 }
1753
Dianne Hackborn906497c2010-05-10 15:57:38 -07001754 private final void updateLruProcessInternalLocked(ProcessRecord app,
1755 boolean oomAdj, boolean updateActivityTime, int bestPos) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 // put it on the LRU to keep track of when it should be exited.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001757 int lrui = mLruProcesses.indexOf(app);
1758 if (lrui >= 0) mLruProcesses.remove(lrui);
1759
1760 int i = mLruProcesses.size()-1;
1761 int skipTop = 0;
1762
Dianne Hackborn906497c2010-05-10 15:57:38 -07001763 app.lruSeq = mLruSeq;
1764
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001765 // compute the new weight for this process.
1766 if (updateActivityTime) {
1767 app.lastActivityTime = SystemClock.uptimeMillis();
1768 }
1769 if (app.activities.size() > 0) {
1770 // If this process has activities, we more strongly want to keep
1771 // it around.
1772 app.lruWeight = app.lastActivityTime;
1773 } else if (app.pubProviders.size() > 0) {
1774 // If this process contains content providers, we want to keep
1775 // it a little more strongly.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001776 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001777 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001778 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001779 } else {
1780 // If this process doesn't have activities, we less strongly
1781 // want to keep it around, and generally want to avoid getting
1782 // in front of any very recently used activities.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001783 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001784 // Also don't let it kick out the first few "real" hidden processes.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001785 skipTop = ProcessList.MIN_HIDDEN_APPS;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001786 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001787
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001788 while (i >= 0) {
1789 ProcessRecord p = mLruProcesses.get(i);
1790 // If this app shouldn't be in front of the first N background
1791 // apps, then skip over that many that are currently hidden.
Dianne Hackborn7d608422011-08-07 16:24:18 -07001792 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001793 skipTop--;
1794 }
Dianne Hackborn906497c2010-05-10 15:57:38 -07001795 if (p.lruWeight <= app.lruWeight || i < bestPos) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08001796 mLruProcesses.add(i+1, app);
1797 break;
1798 }
1799 i--;
1800 }
1801 if (i < 0) {
1802 mLruProcesses.add(0, app);
1803 }
1804
Dianne Hackborn906497c2010-05-10 15:57:38 -07001805 // If the app is currently using a content provider or service,
1806 // bump those processes as well.
1807 if (app.connections.size() > 0) {
1808 for (ConnectionRecord cr : app.connections) {
1809 if (cr.binding != null && cr.binding.service != null
1810 && cr.binding.service.app != null
1811 && cr.binding.service.app.lruSeq != mLruSeq) {
Björn Davidsson90f9e312010-11-18 08:26:27 +01001812 updateLruProcessInternalLocked(cr.binding.service.app, false,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001813 updateActivityTime, i+1);
1814 }
1815 }
1816 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001817 for (int j=app.conProviders.size()-1; j>=0; j--) {
1818 ContentProviderRecord cpr = app.conProviders.get(j).provider;
1819 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) {
Jean-Baptiste Querub8c64052012-06-11 11:01:19 -07001820 updateLruProcessInternalLocked(cpr.proc, false,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07001821 updateActivityTime, i+1);
Dianne Hackborn906497c2010-05-10 15:57:38 -07001822 }
1823 }
1824
Joe Onorato8a9b2202010-02-26 18:56:32 -08001825 //Slog.i(TAG, "Putting proc to front: " + app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 if (oomAdj) {
1827 updateOomAdjLocked();
1828 }
1829 }
1830
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001831 final void updateLruProcessLocked(ProcessRecord app,
Dianne Hackborn906497c2010-05-10 15:57:38 -07001832 boolean oomAdj, boolean updateActivityTime) {
1833 mLruSeq++;
1834 updateLruProcessInternalLocked(app, oomAdj, updateActivityTime, 0);
1835 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001836
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001837 final ProcessRecord getProcessRecordLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 String processName, int uid) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07001839 if (uid == Process.SYSTEM_UID) {
Amith Yamasani0184ce92012-03-28 22:41:41 -07001840 // The system gets to run in any process. If there are multiple
1841 // processes with the same uid, just pick the first (this
1842 // should never happen).
1843 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(
1844 processName);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001845 if (procs == null) return null;
1846 final int N = procs.size();
1847 for (int i = 0; i < N; i++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001848 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i);
Amith Yamasania4a54e22012-04-16 15:44:19 -07001849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 }
1851 ProcessRecord proc = mProcessNames.get(processName, uid);
1852 return proc;
1853 }
1854
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001855 void ensurePackageDexOpt(String packageName) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07001856 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07001857 try {
1858 if (pm.performDexOpt(packageName)) {
1859 mDidDexOpt = true;
1860 }
1861 } catch (RemoteException e) {
1862 }
1863 }
1864
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001865 boolean isNextTransitionForward() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 int transit = mWindowManager.getPendingAppTransition();
1867 return transit == WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
1868 || transit == WindowManagerPolicy.TRANSIT_TASK_OPEN
1869 || transit == WindowManagerPolicy.TRANSIT_TASK_TO_FRONT;
1870 }
1871
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001872 final ProcessRecord startProcessLocked(String processName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 ApplicationInfo info, boolean knownToBeDead, int intentFlags,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001874 String hostingType, ComponentName hostingName, boolean allowWhileBooting,
1875 boolean isolated) {
1876 ProcessRecord app;
1877 if (!isolated) {
1878 app = getProcessRecordLocked(processName, info.uid);
1879 } else {
1880 // If this is an isolated process, it can't re-use an existing process.
1881 app = null;
1882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 // We don't have to do anything more if:
1884 // (1) There is an existing application record; and
1885 // (2) The caller doesn't think it is dead, OR there is no thread
1886 // object attached to it so we know it couldn't have crashed; and
1887 // (3) There is a pid assigned to it, so it is either starting or
1888 // already running.
Joe Onorato8a9b2202010-02-26 18:56:32 -08001889 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 + " app=" + app + " knownToBeDead=" + knownToBeDead
1891 + " thread=" + (app != null ? app.thread : null)
1892 + " pid=" + (app != null ? app.pid : -1));
Magnus Edlund7bb25812010-02-24 15:45:06 +01001893 if (app != null && app.pid > 0) {
1894 if (!knownToBeDead || app.thread == null) {
Dianne Hackborn20cb56e2010-03-04 00:58:29 -08001895 // We already have the app running, or are waiting for it to
1896 // come up (we have a pid but not yet its thread), so keep it.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001897 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001898 // If this is a new package in the process, add the package to the list
1899 app.addPackage(info.packageName);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001900 return app;
1901 } else {
1902 // An application record is attached to a previous process,
1903 // clean it up now.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001904 if (DEBUG_PROCESSES) Slog.v(TAG, "App died: " + app);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07001905 handleAppDiedLocked(app, true, true);
Magnus Edlund7bb25812010-02-24 15:45:06 +01001906 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01001908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 String hostingNameStr = hostingName != null
1910 ? hostingName.flattenToShortString() : null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001911
1912 if (!isolated) {
1913 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) {
1914 // If we are in the background, then check to see if this process
1915 // is bad. If so, we will just silently fail.
1916 if (mBadProcesses.get(info.processName, info.uid) != null) {
1917 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid
1918 + "/" + info.processName);
1919 return null;
1920 }
1921 } else {
1922 // When the user is explicitly starting a process, then clear its
1923 // crash count so that we won't make it bad until they see at
1924 // least one crash dialog again, and make the process good again
1925 // if it had been bad.
1926 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001927 + "/" + info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001928 mProcessCrashTimes.remove(info.processName, info.uid);
1929 if (mBadProcesses.get(info.processName, info.uid) != null) {
1930 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, info.uid,
1931 info.processName);
1932 mBadProcesses.remove(info.processName, info.uid);
1933 if (app != null) {
1934 app.bad = false;
1935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 }
1937 }
1938 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001941 app = newProcessRecordLocked(null, info, processName, isolated);
1942 if (app == null) {
1943 Slog.w(TAG, "Failed making new process record for "
1944 + processName + "/" + info.uid + " isolated=" + isolated);
1945 return null;
1946 }
1947 mProcessNames.put(processName, app.uid, app);
1948 if (isolated) {
1949 mIsolatedProcesses.put(app.uid, app);
1950 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 } else {
1952 // If this is a new package in the process, add the package to the list
1953 app.addPackage(info.packageName);
1954 }
1955
1956 // If the system is not ready yet, then hold off on starting this
1957 // process until it is.
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001958 if (!mProcessesReady
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001959 && !isAllowedWhileBooting(info)
1960 && !allowWhileBooting) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001961 if (!mProcessesOnHold.contains(app)) {
1962 mProcessesOnHold.add(app);
1963 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001964 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 return app;
1966 }
1967
1968 startProcessLocked(app, hostingType, hostingNameStr);
1969 return (app.pid != 0) ? app : null;
1970 }
1971
Dianne Hackborn9acc0302009-08-25 00:27:12 -07001972 boolean isAllowedWhileBooting(ApplicationInfo ai) {
1973 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
1974 }
1975
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 private final void startProcessLocked(ProcessRecord app,
1977 String hostingType, String hostingNameStr) {
1978 if (app.pid > 0 && app.pid != MY_PID) {
1979 synchronized (mPidsSelfLocked) {
1980 mPidsSelfLocked.remove(app.pid);
1981 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
1982 }
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07001983 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 }
1985
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07001986 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
1987 "startProcessLocked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001988 mProcessesOnHold.remove(app);
1989
1990 updateCpuStats();
1991
1992 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1);
1993 mProcDeaths[0] = 0;
1994
1995 try {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08001996 int uid = app.uid;
Amith Yamasani742a6712011-05-04 14:49:28 -07001997
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 int[] gids = null;
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07001999 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002000 if (!app.isolated) {
2001 try {
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002002 final PackageManager pm = mContext.getPackageManager();
2003 gids = pm.getPackageGids(app.info.packageName);
Jeff Sharkeye217ee42012-08-28 16:23:01 -07002004
2005 if (Environment.isExternalStorageEmulated()) {
2006 if (pm.checkPermission(
2007 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE,
2008 app.info.packageName) == PERMISSION_GRANTED) {
2009 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL;
2010 } else {
2011 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER;
2012 }
2013 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002014 } catch (PackageManager.NameNotFoundException e) {
2015 Slog.w(TAG, "Unable to retrieve gids", e);
2016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017 }
2018 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) {
2019 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2020 && mTopComponent != null
2021 && app.processName.equals(mTopComponent.getPackageName())) {
2022 uid = 0;
2023 }
2024 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL
2025 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
2026 uid = 0;
2027 }
2028 }
2029 int debugFlags = 0;
2030 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
2031 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
Elliott Hughesfa36aee2011-06-17 14:39:41 -07002032 // Also turn on CheckJNI for debuggable apps. It's quite
2033 // awkward to turn on otherwise.
2034 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 }
Ben Cheng6c0afff2010-02-14 16:18:56 -08002036 // Run the app in safe mode if its manifest requests so or the
2037 // system is booted in safe mode.
2038 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 ||
2039 Zygote.systemInSafeMode == true) {
Ben Cheng23085b72010-02-08 16:06:32 -08002040 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
2041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 if ("1".equals(SystemProperties.get("debug.checkjni"))) {
2043 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
2044 }
Elliott Hughesae07ecf2011-07-06 17:33:27 -07002045 if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
2046 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
2047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 if ("1".equals(SystemProperties.get("debug.assert"))) {
2049 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
2050 }
Jeff Brown3f9dd282011-07-08 20:02:19 -07002051
2052 // Start the process. It will either succeed and return a result containing
2053 // the PID of the new process, or else throw a RuntimeException.
2054 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread",
Jeff Sharkey5b1ada22012-08-14 18:47:09 -07002055 app.processName, uid, uid, gids, debugFlags, mountExternal,
Stephen Smalley83d9eda2012-01-13 08:34:17 -05002056 app.info.targetSdkVersion, null, null);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 BatteryStatsImpl bs = app.batteryStats.getBatteryStats();
2059 synchronized (bs) {
2060 if (bs.isOnBattery()) {
2061 app.batteryStats.incStartsLocked();
2062 }
2063 }
2064
Jeff Brown3f9dd282011-07-08 20:02:19 -07002065 EventLog.writeEvent(EventLogTags.AM_PROC_START, startResult.pid, uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 app.processName, hostingType,
2067 hostingNameStr != null ? hostingNameStr : "");
2068
2069 if (app.persistent) {
Jeff Brown3f9dd282011-07-08 20:02:19 -07002070 Watchdog.getInstance().processStarted(app.processName, startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002071 }
2072
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07002073 StringBuilder buf = mStringBuilder;
2074 buf.setLength(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 buf.append("Start proc ");
2076 buf.append(app.processName);
2077 buf.append(" for ");
2078 buf.append(hostingType);
2079 if (hostingNameStr != null) {
2080 buf.append(" ");
2081 buf.append(hostingNameStr);
2082 }
2083 buf.append(": pid=");
Jeff Brown3f9dd282011-07-08 20:02:19 -07002084 buf.append(startResult.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 buf.append(" uid=");
2086 buf.append(uid);
2087 buf.append(" gids={");
2088 if (gids != null) {
2089 for (int gi=0; gi<gids.length; gi++) {
2090 if (gi != 0) buf.append(", ");
2091 buf.append(gids[gi]);
2092
2093 }
2094 }
2095 buf.append("}");
Joe Onorato8a9b2202010-02-26 18:56:32 -08002096 Slog.i(TAG, buf.toString());
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002097 app.setPid(startResult.pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07002098 app.usingWrapper = startResult.usingWrapper;
2099 app.removed = false;
2100 synchronized (mPidsSelfLocked) {
2101 this.mPidsSelfLocked.put(startResult.pid, app);
2102 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
2103 msg.obj = app;
2104 mHandler.sendMessageDelayed(msg, startResult.usingWrapper
2105 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 }
2107 } catch (RuntimeException e) {
2108 // XXX do better error recovery.
Dianne Hackbornf88dd0b2012-08-08 17:20:32 -07002109 app.setPid(0);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002110 Slog.e(TAG, "Failure starting process " + app.processName, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 }
2112 }
2113
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002114 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 if (resumed) {
2116 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity);
2117 } else {
2118 mUsageStatsService.notePauseComponent(resumedComponent.realActivity);
2119 }
2120 }
2121
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002122 boolean startHomeActivityLocked(int userId, UserStartedState startingUser) {
Mike Lockwooda8f767a2011-08-31 14:32:37 -04002123 if (mHeadless) {
2124 // Added because none of the other calls to ensureBootCompleted seem to fire
2125 // when running headless.
2126 ensureBootCompleted();
2127 return false;
2128 }
2129
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002130 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL
2131 && mTopAction == null) {
2132 // We are running in factory test mode, but unable to find
2133 // the factory test app, so just sit around displaying the
2134 // error message and don't try to start anything.
2135 return false;
2136 }
2137 Intent intent = new Intent(
2138 mTopAction,
2139 mTopData != null ? Uri.parse(mTopData) : null);
2140 intent.setComponent(mTopComponent);
2141 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
2142 intent.addCategory(Intent.CATEGORY_HOME);
2143 }
2144 ActivityInfo aInfo =
2145 intent.resolveActivityInfo(mContext.getPackageManager(),
2146 STOCK_PM_FLAGS);
2147 if (aInfo != null) {
2148 intent.setComponent(new ComponentName(
2149 aInfo.applicationInfo.packageName, aInfo.name));
2150 // Don't do this if the home app is currently being
2151 // instrumented.
Amith Yamasani742a6712011-05-04 14:49:28 -07002152 aInfo = new ActivityInfo(aInfo);
2153 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002154 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
2155 aInfo.applicationInfo.uid);
2156 if (app == null || app.instrumentationClass == null) {
2157 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002158 mMainStack.startActivityLocked(null, intent, null, aInfo,
2159 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002160 }
2161 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002162 if (startingUser != null) {
2163 mMainStack.addStartingUserLocked(startingUser);
2164 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002165
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002166 return true;
2167 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002168
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002169 /**
2170 * Starts the "new version setup screen" if appropriate.
2171 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002172 void startSetupActivityLocked() {
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002173 // Only do this once per boot.
2174 if (mCheckedForSetup) {
2175 return;
2176 }
2177
2178 // We will show this screen if the current one is a different
2179 // version than the last one shown, and we are not running in
2180 // low-level factory test mode.
2181 final ContentResolver resolver = mContext.getContentResolver();
2182 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL &&
2183 Settings.Secure.getInt(resolver,
2184 Settings.Secure.DEVICE_PROVISIONED, 0) != 0) {
2185 mCheckedForSetup = true;
2186
2187 // See if we should be showing the platform update setup UI.
2188 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP);
2189 List<ResolveInfo> ris = mSelf.mContext.getPackageManager()
2190 .queryIntentActivities(intent, PackageManager.GET_META_DATA);
2191
2192 // We don't allow third party apps to replace this.
2193 ResolveInfo ri = null;
2194 for (int i=0; ris != null && i<ris.size(); i++) {
2195 if ((ris.get(i).activityInfo.applicationInfo.flags
2196 & ApplicationInfo.FLAG_SYSTEM) != 0) {
2197 ri = ris.get(i);
2198 break;
2199 }
2200 }
2201
2202 if (ri != null) {
2203 String vers = ri.activityInfo.metaData != null
2204 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION)
2205 : null;
2206 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) {
2207 vers = ri.activityInfo.applicationInfo.metaData.getString(
2208 Intent.METADATA_SETUP_VERSION);
2209 }
2210 String lastVers = Settings.Secure.getString(
2211 resolver, Settings.Secure.LAST_SETUP_SHOWN);
2212 if (vers != null && !vers.equals(lastVers)) {
2213 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2214 intent.setComponent(new ComponentName(
2215 ri.activityInfo.packageName, ri.activityInfo.name));
Dianne Hackborna4972e92012-03-14 10:38:05 -07002216 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo,
2217 null, null, 0, 0, 0, 0, null, false, null);
Dianne Hackbornd7cd29d2009-07-01 11:22:45 -07002218 }
2219 }
2220 }
2221 }
2222
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002223 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002224 return mCompatModePackages.compatibilityInfoForPackageLocked(ai);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002225 }
2226
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002227 void enforceNotIsolatedCaller(String caller) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002228 if (UserHandle.isIsolated(Binder.getCallingUid())) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002229 throw new SecurityException("Isolated process not allowed to call " + caller);
2230 }
2231 }
2232
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002233 public int getFrontActivityScreenCompatMode() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002234 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode");
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002235 synchronized (this) {
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002236 return mCompatModePackages.getFrontActivityScreenCompatModeLocked();
2237 }
2238 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002239
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002240 public void setFrontActivityScreenCompatMode(int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002241 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2242 "setFrontActivityScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002243 synchronized (this) {
2244 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode);
2245 }
2246 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002247
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002248 public int getPackageScreenCompatMode(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002249 enforceNotIsolatedCaller("getPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002250 synchronized (this) {
2251 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName);
2252 }
2253 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002254
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002255 public void setPackageScreenCompatMode(String packageName, int mode) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002256 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2257 "setPackageScreenCompatMode");
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -07002258 synchronized (this) {
2259 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04002260 }
2261 }
2262
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002263 public boolean getPackageAskScreenCompat(String packageName) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002264 enforceNotIsolatedCaller("getPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002265 synchronized (this) {
2266 return mCompatModePackages.getPackageAskCompatModeLocked(packageName);
2267 }
2268 }
2269
2270 public void setPackageAskScreenCompat(String packageName, boolean ask) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002271 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY,
2272 "setPackageAskScreenCompat");
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07002273 synchronized (this) {
2274 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask);
2275 }
2276 }
2277
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002278 void reportResumedActivityLocked(ActivityRecord r) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002279 //Slog.i(TAG, "**** REPORT RESUME: " + r);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002280 updateUsageStats(r, true);
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002283 private void dispatchProcessesChanged() {
2284 int N;
2285 synchronized (this) {
2286 N = mPendingProcessChanges.size();
2287 if (mActiveProcessChanges.length < N) {
2288 mActiveProcessChanges = new ProcessChangeItem[N];
2289 }
2290 mPendingProcessChanges.toArray(mActiveProcessChanges);
2291 mAvailProcessChanges.addAll(mPendingProcessChanges);
2292 mPendingProcessChanges.clear();
2293 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes");
2294 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002295 int i = mProcessObservers.beginBroadcast();
2296 while (i > 0) {
2297 i--;
2298 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2299 if (observer != null) {
2300 try {
Dianne Hackborna93c2c12012-05-31 15:29:36 -07002301 for (int j=0; j<N; j++) {
2302 ProcessChangeItem item = mActiveProcessChanges[j];
2303 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) {
2304 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid="
2305 + item.pid + " uid=" + item.uid + ": "
2306 + item.foregroundActivities);
2307 observer.onForegroundActivitiesChanged(item.pid, item.uid,
2308 item.foregroundActivities);
2309 }
2310 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) {
2311 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid="
2312 + item.pid + " uid=" + item.uid + ": " + item.importance);
2313 observer.onImportanceChanged(item.pid, item.uid,
2314 item.importance);
2315 }
2316 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07002317 } catch (RemoteException e) {
2318 }
2319 }
2320 }
2321 mProcessObservers.finishBroadcast();
2322 }
2323
2324 private void dispatchProcessDied(int pid, int uid) {
2325 int i = mProcessObservers.beginBroadcast();
2326 while (i > 0) {
2327 i--;
2328 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i);
2329 if (observer != null) {
2330 try {
2331 observer.onProcessDied(pid, uid);
2332 } catch (RemoteException e) {
2333 }
2334 }
2335 }
2336 mProcessObservers.finishBroadcast();
2337 }
2338
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002339 final void doPendingActivityLaunchesLocked(boolean doResume) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002340 final int N = mPendingActivityLaunches.size();
2341 if (N <= 0) {
2342 return;
2343 }
2344 for (int i=0; i<N; i++) {
2345 PendingActivityLaunch pal = mPendingActivityLaunches.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002346 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002347 pal.startFlags, doResume && i == (N-1), null);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07002348 }
2349 mPendingActivityLaunches.clear();
2350 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002351
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002352 public final int startActivity(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002353 Intent intent, String resolvedType, IBinder resultTo,
2354 String resultWho, int requestCode, int startFlags,
2355 String profileFile, ParcelFileDescriptor profileFd, Bundle options) {
Amith Yamasani82644082012-08-03 13:09:11 -07002356 return startActivityAsUser(caller, intent, resolvedType, resultTo, resultWho, requestCode,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002357 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId());
Amith Yamasani82644082012-08-03 13:09:11 -07002358 }
2359
2360 public final int startActivityAsUser(IApplicationThread caller,
2361 Intent intent, String resolvedType, IBinder resultTo,
2362 String resultWho, int requestCode, int startFlags,
2363 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002364 enforceNotIsolatedCaller("startActivity");
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002365 if (userId != UserHandle.getCallingUserId()) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07002366 userId = handleIncomingUserLocked(Binder.getCallingPid(), Binder.getCallingUid(), userId,
2367 false, true, "startActivity", null);
Amith Yamasani82644082012-08-03 13:09:11 -07002368 } else {
2369 if (intent.getCategories() != null
2370 && intent.getCategories().contains(Intent.CATEGORY_HOME)) {
2371 // Requesting home, set the identity to the current user
2372 // HACK!
2373 userId = mCurrentUserId;
2374 } else {
2375 // TODO: Fix this in a better way - calls coming from SystemUI should probably carry
2376 // the current user's userId
2377 if (Binder.getCallingUid() < Process.FIRST_APPLICATION_UID) {
2378 userId = 0;
2379 } else {
2380 userId = Binder.getOrigCallingUser();
2381 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002382 }
2383 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002384 return mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002385 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2386 null, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002387 }
2388
2389 public final WaitResult startActivityAndWait(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002390 Intent intent, String resolvedType, IBinder resultTo,
2391 String resultWho, int requestCode, int startFlags, String profileFile,
2392 ParcelFileDescriptor profileFd, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002393 enforceNotIsolatedCaller("startActivityAndWait");
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002394 WaitResult res = new WaitResult();
Amith Yamasani742a6712011-05-04 14:49:28 -07002395 int userId = Binder.getOrigCallingUser();
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002396 mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002397 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd,
2398 res, null, options, userId);
Dianne Hackborn8f7f35e2010-02-25 18:48:12 -08002399 return res;
2400 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08002401
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002402 public final int startActivityWithConfig(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002403 Intent intent, String resolvedType, IBinder resultTo,
2404 String resultWho, int requestCode, int startFlags, Configuration config,
2405 Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002406 enforceNotIsolatedCaller("startActivityWithConfig");
Amith Yamasani742a6712011-05-04 14:49:28 -07002407 int ret = mMainStack.startActivityMayWait(caller, -1, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002408 resultTo, resultWho, requestCode, startFlags,
2409 null, null, null, config, options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002410 return ret;
Dianne Hackborn2ccda4d2010-03-22 21:49:15 -07002411 }
2412
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002413 public int startActivityIntentSender(IApplicationThread caller,
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002414 IntentSender intent, Intent fillInIntent, String resolvedType,
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002415 IBinder resultTo, String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002416 int flagsMask, int flagsValues, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002417 enforceNotIsolatedCaller("startActivityIntentSender");
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002418 // Refuse possible leaked file descriptors
2419 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) {
2420 throw new IllegalArgumentException("File descriptors passed in Intent");
2421 }
2422
2423 IIntentSender sender = intent.getTarget();
2424 if (!(sender instanceof PendingIntentRecord)) {
2425 throw new IllegalArgumentException("Bad PendingIntent object");
2426 }
2427
2428 PendingIntentRecord pir = (PendingIntentRecord)sender;
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002429
2430 synchronized (this) {
2431 // If this is coming from the currently resumed activity, it is
2432 // effectively saying that app switches are allowed at this point.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002433 if (mMainStack.mResumedActivity != null
2434 && mMainStack.mResumedActivity.info.applicationInfo.uid ==
Dianne Hackbornfa82f222009-09-17 15:14:12 -07002435 Binder.getCallingUid()) {
2436 mAppSwitchesAllowedTime = 0;
2437 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002438 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002439 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null,
2440 resultTo, resultWho, requestCode, flagsMask, flagsValues, options);
Amith Yamasani742a6712011-05-04 14:49:28 -07002441 return ret;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -07002442 }
2443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 public boolean startNextMatchingActivity(IBinder callingActivity,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002445 Intent intent, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 // Refuse possible leaked file descriptors
2447 if (intent != null && intent.hasFileDescriptors() == true) {
2448 throw new IllegalArgumentException("File descriptors passed in Intent");
2449 }
2450
2451 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002452 ActivityRecord r = mMainStack.isInStackLocked(callingActivity);
2453 if (r == null) {
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 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 if (r.app == null || r.app.thread == null) {
2458 // The caller is not running... d'oh!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002459 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 return false;
2461 }
2462 intent = new Intent(intent);
2463 // The caller is not allowed to change the data.
2464 intent.setDataAndType(r.intent.getData(), r.intent.getType());
2465 // And we are resetting to find the next component...
2466 intent.setComponent(null);
2467
2468 ActivityInfo aInfo = null;
2469 try {
2470 List<ResolveInfo> resolves =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002471 AppGlobals.getPackageManager().queryIntentActivities(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 intent, r.resolvedType,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002473 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002474 UserHandle.getCallingUserId());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475
2476 // Look for the original activity in the list...
2477 final int N = resolves != null ? resolves.size() : 0;
2478 for (int i=0; i<N; i++) {
2479 ResolveInfo rInfo = resolves.get(i);
2480 if (rInfo.activityInfo.packageName.equals(r.packageName)
2481 && rInfo.activityInfo.name.equals(r.info.name)) {
2482 // We found the current one... the next matching is
2483 // after it.
2484 i++;
2485 if (i<N) {
2486 aInfo = resolves.get(i).activityInfo;
2487 }
2488 break;
2489 }
2490 }
2491 } catch (RemoteException e) {
2492 }
2493
2494 if (aInfo == null) {
2495 // Nobody who is next!
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002496 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 return false;
2498 }
2499
2500 intent.setComponent(new ComponentName(
2501 aInfo.applicationInfo.packageName, aInfo.name));
2502 intent.setFlags(intent.getFlags()&~(
2503 Intent.FLAG_ACTIVITY_FORWARD_RESULT|
2504 Intent.FLAG_ACTIVITY_CLEAR_TOP|
2505 Intent.FLAG_ACTIVITY_MULTIPLE_TASK|
2506 Intent.FLAG_ACTIVITY_NEW_TASK));
2507
2508 // Okay now we need to start the new activity, replacing the
2509 // currently running activity. This is a little tricky because
2510 // we want to start the new one as if the current one is finished,
2511 // but not finish the current one first so that there is no flicker.
2512 // And thus...
2513 final boolean wasFinishing = r.finishing;
2514 r.finishing = true;
2515
2516 // Propagate reply information over to the new activity.
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002517 final ActivityRecord resultTo = r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 final String resultWho = r.resultWho;
2519 final int requestCode = r.requestCode;
2520 r.resultTo = null;
2521 if (resultTo != null) {
2522 resultTo.removeResultsLocked(r, resultWho, requestCode);
2523 }
2524
2525 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002526 int res = mMainStack.startActivityLocked(r.app.thread, intent,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002527 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null,
2528 resultWho, requestCode, -1, r.launchedFromUid, 0,
2529 options, false, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 Binder.restoreCallingIdentity(origId);
2531
2532 r.finishing = wasFinishing;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002533 if (res != ActivityManager.START_SUCCESS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 return false;
2535 }
2536 return true;
2537 }
2538 }
2539
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002540 public final int startActivityInPackage(int uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002542 String resultWho, int requestCode, int startFlags, Bundle options) {
Dianne Hackborn2d91af02009-07-16 13:34:33 -07002543
2544 // This is so super not safe, that only the system (or okay root)
2545 // can do it.
2546 final int callingUid = Binder.getCallingUid();
2547 if (callingUid != 0 && callingUid != Process.myUid()) {
2548 throw new SecurityException(
2549 "startActivityInPackage only available to the system");
2550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551
Amith Yamasani742a6712011-05-04 14:49:28 -07002552 int ret = mMainStack.startActivityMayWait(null, uid, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002553 resultTo, resultWho, requestCode, startFlags,
Amith Yamasani7300dbe2012-08-17 14:17:57 -07002554 null, null, null, null, options, UserHandle.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002555 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002556 }
2557
2558 public final int startActivities(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002559 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08002560 enforceNotIsolatedCaller("startActivities");
Amith Yamasani742a6712011-05-04 14:49:28 -07002561 int ret = mMainStack.startActivities(caller, -1, intents, resolvedTypes, resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002562 options, Binder.getOrigCallingUser());
Amith Yamasani742a6712011-05-04 14:49:28 -07002563 return ret;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002564 }
2565
2566 public final int startActivitiesInPackage(int uid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002567 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
2568 Bundle options) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002569
2570 // This is so super not safe, that only the system (or okay root)
2571 // can do it.
2572 final int callingUid = Binder.getCallingUid();
2573 if (callingUid != 0 && callingUid != Process.myUid()) {
2574 throw new SecurityException(
2575 "startActivityInPackage only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002577 int ret = mMainStack.startActivities(null, uid, intents, resolvedTypes, resultTo,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002578 options, UserHandle.getUserId(uid));
Amith Yamasani742a6712011-05-04 14:49:28 -07002579 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 }
2581
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002582 final void addRecentTaskLocked(TaskRecord task) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 int N = mRecentTasks.size();
Dianne Hackborn7c0e75e2010-12-21 19:15:40 -08002584 // Quick case: check if the top-most recent task is the same.
2585 if (N > 0 && mRecentTasks.get(0) == task) {
2586 return;
2587 }
2588 // Remove any existing entries that are the same kind of task.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 for (int i=0; i<N; i++) {
2590 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07002591 if (task.userId == tr.userId
2592 && ((task.affinity != null && task.affinity.equals(tr.affinity))
2593 || (task.intent != null && task.intent.filterEquals(tr.intent)))) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 mRecentTasks.remove(i);
2595 i--;
2596 N--;
2597 if (task.intent == null) {
2598 // If the new recent task we are adding is not fully
2599 // specified, then replace it with the existing recent task.
2600 task = tr;
2601 }
2602 }
2603 }
2604 if (N >= MAX_RECENT_TASKS) {
2605 mRecentTasks.remove(N-1);
2606 }
2607 mRecentTasks.add(0, task);
2608 }
2609
2610 public void setRequestedOrientation(IBinder token,
2611 int requestedOrientation) {
2612 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002613 ActivityRecord r = mMainStack.isInStackLocked(token);
2614 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 return;
2616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002618 mWindowManager.setAppOrientation(r.appToken, requestedOrientation);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002619 Configuration config = mWindowManager.updateOrientationFromAppTokens(
The Android Open Source Project10592532009-03-18 17:39:46 -07002620 mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002621 r.mayFreezeScreenLocked(r.app) ? r.appToken : null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002622 if (config != null) {
2623 r.frozenBeforeDestroy = true;
Dianne Hackborn813075a62011-11-14 17:45:19 -08002624 if (!updateConfigurationLocked(config, r, false, false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002625 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 }
2627 }
2628 Binder.restoreCallingIdentity(origId);
2629 }
2630 }
2631
2632 public int getRequestedOrientation(IBinder token) {
2633 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002634 ActivityRecord r = mMainStack.isInStackLocked(token);
2635 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002636 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
2637 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002638 return mWindowManager.getAppOrientation(r.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002639 }
2640 }
2641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 /**
2643 * This is the internal entry point for handling Activity.finish().
2644 *
2645 * @param token The Binder token referencing the Activity we want to finish.
2646 * @param resultCode Result code, if any, from this Activity.
2647 * @param resultData Result data (Intent), if any, from this Activity.
2648 *
Alexey Tarasov83bad3d2009-08-12 15:05:43 +11002649 * @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 -08002650 */
2651 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) {
2652 // Refuse possible leaked file descriptors
2653 if (resultData != null && resultData.hasFileDescriptors() == true) {
2654 throw new IllegalArgumentException("File descriptors passed in Intent");
2655 }
2656
2657 synchronized(this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002658 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 // Find the first activity that is not finishing.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002660 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 if (next != null) {
2662 // ask watcher if this is allowed
2663 boolean resumeOK = true;
2664 try {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002665 resumeOK = mController.activityResuming(next.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002666 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07002667 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002668 }
2669
2670 if (!resumeOK) {
2671 return false;
2672 }
2673 }
2674 }
2675 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002676 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 resultData, "app-request");
2678 Binder.restoreCallingIdentity(origId);
2679 return res;
2680 }
2681 }
2682
Dianne Hackborn860755f2010-06-03 18:47:52 -07002683 public final void finishHeavyWeightApp() {
2684 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2685 != PackageManager.PERMISSION_GRANTED) {
2686 String msg = "Permission Denial: finishHeavyWeightApp() from pid="
2687 + Binder.getCallingPid()
2688 + ", uid=" + Binder.getCallingUid()
2689 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2690 Slog.w(TAG, msg);
2691 throw new SecurityException(msg);
2692 }
2693
2694 synchronized(this) {
2695 if (mHeavyWeightProcess == null) {
2696 return;
2697 }
2698
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002699 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>(
Dianne Hackborn860755f2010-06-03 18:47:52 -07002700 mHeavyWeightProcess.activities);
2701 for (int i=0; i<activities.size(); i++) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07002702 ActivityRecord r = activities.get(i);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002703 if (!r.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002704 int index = mMainStack.indexOfTokenLocked(r.appToken);
Dianne Hackborn860755f2010-06-03 18:47:52 -07002705 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002706 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED,
Dianne Hackborn860755f2010-06-03 18:47:52 -07002707 null, "finish-heavy");
2708 }
2709 }
2710 }
2711
2712 mHeavyWeightProcess = null;
2713 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
2714 }
2715 }
2716
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002717 public void crashApplication(int uid, int initialPid, String packageName,
2718 String message) {
2719 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
2720 != PackageManager.PERMISSION_GRANTED) {
2721 String msg = "Permission Denial: crashApplication() from pid="
2722 + Binder.getCallingPid()
2723 + ", uid=" + Binder.getCallingUid()
2724 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
2725 Slog.w(TAG, msg);
2726 throw new SecurityException(msg);
2727 }
2728
2729 synchronized(this) {
2730 ProcessRecord proc = null;
2731
2732 // Figure out which process to kill. We don't trust that initialPid
2733 // still has any relation to current pids, so must scan through the
2734 // list.
2735 synchronized (mPidsSelfLocked) {
2736 for (int i=0; i<mPidsSelfLocked.size(); i++) {
2737 ProcessRecord p = mPidsSelfLocked.valueAt(i);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08002738 if (p.uid != uid) {
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002739 continue;
2740 }
2741 if (p.pid == initialPid) {
2742 proc = p;
2743 break;
2744 }
2745 for (String str : p.pkgList) {
2746 if (str.equals(packageName)) {
2747 proc = p;
2748 }
2749 }
2750 }
2751 }
2752
2753 if (proc == null) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07002754 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002755 + " initialPid=" + initialPid
2756 + " packageName=" + packageName);
2757 return;
2758 }
2759
2760 if (proc.thread != null) {
Dianne Hackborn9f531192010-08-04 17:48:03 -07002761 if (proc.pid == Process.myPid()) {
2762 Log.w(TAG, "crashApplication: trying to crash self!");
2763 return;
2764 }
Dianne Hackborn9d39d0c2010-06-24 15:57:42 -07002765 long ident = Binder.clearCallingIdentity();
2766 try {
2767 proc.thread.scheduleCrash(message);
2768 } catch (RemoteException e) {
2769 }
2770 Binder.restoreCallingIdentity(ident);
2771 }
2772 }
2773 }
2774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002775 public final void finishSubActivity(IBinder token, String resultWho,
2776 int requestCode) {
2777 synchronized(this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002778 final long origId = Binder.clearCallingIdentity();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002779 mMainStack.finishSubActivityLocked(token, resultWho, requestCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 Binder.restoreCallingIdentity(origId);
2781 }
2782 }
2783
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07002784 public boolean finishActivityAffinity(IBinder token) {
2785 synchronized(this) {
2786 final long origId = Binder.clearCallingIdentity();
2787 boolean res = mMainStack.finishActivityAffinityLocked(token);
2788 Binder.restoreCallingIdentity(origId);
2789 return res;
2790 }
2791 }
2792
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002793 public boolean willActivityBeVisible(IBinder token) {
2794 synchronized(this) {
2795 int i;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002796 for (i=mMainStack.mHistory.size()-1; i>=0; i--) {
2797 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002798 if (r.appToken == token) {
Dianne Hackborn061d58a2010-03-12 15:07:06 -08002799 return true;
2800 }
2801 if (r.fullscreen && !r.finishing) {
2802 return false;
2803 }
2804 }
2805 return true;
2806 }
2807 }
2808
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002809 public void overridePendingTransition(IBinder token, String packageName,
2810 int enterAnim, int exitAnim) {
2811 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002812 ActivityRecord self = mMainStack.isInStackLocked(token);
2813 if (self == null) {
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002814 return;
2815 }
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002816
2817 final long origId = Binder.clearCallingIdentity();
2818
2819 if (self.state == ActivityState.RESUMED
2820 || self.state == ActivityState.PAUSING) {
2821 mWindowManager.overridePendingAppTransition(packageName,
Dianne Hackborn84375872012-06-01 19:03:50 -07002822 enterAnim, exitAnim, null);
Dianne Hackborn3b3e1452009-09-24 19:22:12 -07002823 }
2824
2825 Binder.restoreCallingIdentity(origId);
2826 }
2827 }
2828
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 * Main function for removing an existing process from the activity manager
2831 * as a result of that process going away. Clears out all connections
2832 * to the process.
2833 */
2834 private final void handleAppDiedLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002835 boolean restarting, boolean allowRestart) {
2836 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 if (!restarting) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002838 mLruProcesses.remove(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 }
2840
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002841 if (mProfileProc == app) {
2842 clearProfilerLocked();
2843 }
2844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 // Just in case...
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002846 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) {
2847 if (DEBUG_PAUSE) Slog.v(TAG, "App died while pausing: " +mMainStack.mPausingActivity);
2848 mMainStack.mPausingActivity = null;
2849 }
2850 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) {
2851 mMainStack.mLastPausedActivity = null;
2852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853
2854 // Remove this application's activities from active lists.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002855 mMainStack.removeHistoryRecordsForAppLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856
2857 boolean atTop = true;
2858 boolean hasVisibleActivities = false;
2859
2860 // Clean out the history list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002861 int i = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08002862 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 TAG, "Removing app " + app + " from history with " + i + " entries");
2864 while (i > 0) {
2865 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002866 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002867 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 TAG, "Record #" + i + " " + r + ": app=" + r.app);
2869 if (r.app == app) {
2870 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002871 if (ActivityStack.DEBUG_ADD_REMOVE) {
2872 RuntimeException here = new RuntimeException("here");
2873 here.fillInStackTrace();
2874 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
2875 + ": haveState=" + r.haveState
2876 + " stateNotNeeded=" + r.stateNotNeeded
2877 + " finishing=" + r.finishing
2878 + " state=" + r.state, here);
2879 }
2880 if (!r.finishing) {
2881 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -08002882 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
2883 System.identityHashCode(r),
2884 r.task.taskId, r.shortComponentName,
2885 "proc died without state saved");
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002886 }
Dianne Hackborn5c607432012-02-28 14:44:19 -08002887 mMainStack.removeActivityFromHistoryLocked(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888
2889 } else {
2890 // We have the current state for this activity, so
2891 // it can be restarted later when needed.
Joe Onorato8a9b2202010-02-26 18:56:32 -08002892 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 TAG, "Keeping entry, setting app to null");
2894 if (r.visible) {
2895 hasVisibleActivities = true;
2896 }
2897 r.app = null;
2898 r.nowVisible = false;
2899 if (!r.haveState) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002900 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
2901 "App died, clearing saved state of " + r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 r.icicle = null;
2903 }
2904 }
2905
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002906 r.stack.cleanUpActivityLocked(r, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 }
2908 atTop = false;
2909 }
2910
2911 app.activities.clear();
2912
2913 if (app.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002914 Slog.w(TAG, "Crash of app " + app.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 + " running instrumentation " + app.instrumentationClass);
2916 Bundle info = new Bundle();
2917 info.putString("shortMsg", "Process crashed.");
2918 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info);
2919 }
2920
2921 if (!restarting) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002922 if (!mMainStack.resumeTopActivityLocked(null)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 // If there was nothing to resume, and we are not already
2924 // restarting this process, but there is a visible activity that
2925 // is hosted by the process... then make sure all visible
2926 // activities are running, taking care of restarting this
2927 // process.
2928 if (hasVisibleActivities) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002929 mMainStack.ensureActivitiesVisibleLocked(null, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 }
2931 }
2932 }
2933 }
2934
2935 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) {
2936 IBinder threadBinder = thread.asBinder();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 // Find the application record.
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002938 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2939 ProcessRecord rec = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 if (rec.thread != null && rec.thread.asBinder() == threadBinder) {
2941 return i;
2942 }
2943 }
2944 return -1;
2945 }
2946
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002947 final ProcessRecord getRecordForAppLocked(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 IApplicationThread thread) {
2949 if (thread == null) {
2950 return null;
2951 }
2952
2953 int appIndex = getLRURecordIndexForAppLocked(thread);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002954 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002955 }
2956
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002957 final void appDiedLocked(ProcessRecord app, int pid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002958 IApplicationThread thread) {
2959
2960 mProcDeaths[0]++;
2961
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07002962 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
2963 synchronized (stats) {
2964 stats.noteProcessDiedLocked(app.info.uid, pid);
2965 }
2966
Magnus Edlund7bb25812010-02-24 15:45:06 +01002967 // Clean up already done if the process has been re-started.
2968 if (app.pid == pid && app.thread != null &&
2969 app.thread.asBinder() == thread.asBinder()) {
Dianne Hackborn906497c2010-05-10 15:57:38 -07002970 if (!app.killedBackground) {
2971 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
2972 + ") has died.");
2973 }
Doug Zongker2bec3d42009-12-04 12:52:44 -08002974 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Joe Onorato8a9b2202010-02-26 18:56:32 -08002975 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 TAG, "Dying app: " + app + ", pid: " + pid
2977 + ", thread: " + thread.asBinder());
2978 boolean doLowMem = app.instrumentationClass == null;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07002979 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980
2981 if (doLowMem) {
2982 // If there are no longer any background processes running,
2983 // and the app that died was not running instrumentation,
2984 // then tell everyone we are now low on memory.
2985 boolean haveBg = false;
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002986 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2987 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn7d608422011-08-07 16:24:18 -07002988 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002989 haveBg = true;
2990 break;
2991 }
2992 }
2993
2994 if (!haveBg) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002995 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size());
Dianne Hackbornfd12af42009-08-27 00:44:33 -07002996 long now = SystemClock.uptimeMillis();
Dianne Hackborndd71fc82009-12-16 19:24:32 -08002997 for (int i=mLruProcesses.size()-1; i>=0; i--) {
2998 ProcessRecord rec = mLruProcesses.get(i);
Dianne Hackborn36124872009-10-08 16:22:03 -07002999 if (rec != app && rec.thread != null &&
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003000 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) {
3001 // The low memory report is overriding any current
3002 // state for a GC request. Make sure to do
Dianne Hackborn32907cf2010-06-10 17:50:20 -07003003 // heavy/important/visible/foreground processes first.
Dianne Hackborn7d608422011-08-07 16:24:18 -07003004 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003005 rec.lastRequestedGc = 0;
3006 } else {
3007 rec.lastRequestedGc = rec.lastLowMemory;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003009 rec.reportLowMemory = true;
3010 rec.lastLowMemory = now;
3011 mProcessesToGc.remove(rec);
3012 addProcessToGcListLocked(rec);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 }
3014 }
Dianne Hackborn04d6db32011-11-04 20:07:24 -07003015 mHandler.sendEmptyMessage(REPORT_MEM_USAGE);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07003016 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 }
3018 }
Magnus Edlund7bb25812010-02-24 15:45:06 +01003019 } else if (app.pid != pid) {
3020 // A new process has already been started.
Joe Onorato8a9b2202010-02-26 18:56:32 -08003021 Slog.i(TAG, "Process " + app.processName + " (pid " + pid
Magnus Edlund7bb25812010-02-24 15:45:06 +01003022 + ") has died and restarted (pid " + app.pid + ").");
Dianne Hackborn28a8c2b2010-03-01 11:30:02 -08003023 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.pid, app.processName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003024 } else if (DEBUG_PROCESSES) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003025 Slog.d(TAG, "Received spurious death notification for thread "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 + thread.asBinder());
3027 }
3028 }
3029
Dan Egnor42471dd2010-01-07 17:25:22 -08003030 /**
3031 * If a stack trace dump file is configured, dump process stack traces.
Christopher Tate6ee412d2010-05-28 12:01:56 -07003032 * @param clearTraces causes the dump file to be erased prior to the new
3033 * traces being written, if true; when false, the new traces will be
3034 * appended to any existing file content.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003035 * @param firstPids of dalvik VM processes to dump stack traces for first
3036 * @param lastPids of dalvik VM processes to dump stack traces for last
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003037 * @param nativeProcs optional list of native process names to dump stack crawls
Dan Egnor42471dd2010-01-07 17:25:22 -08003038 * @return file containing stack traces, or null if no dump file is configured
3039 */
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003040 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003041 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003042 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3043 if (tracesPath == null || tracesPath.length() == 0) {
3044 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003046
3047 File tracesFile = new File(tracesPath);
3048 try {
3049 File tracesDir = tracesFile.getParentFile();
rpcraigec7ed14c2012-07-25 13:10:37 -04003050 if (!tracesDir.exists()) {
3051 tracesFile.mkdirs();
3052 if (!SELinux.restorecon(tracesDir)) {
3053 return null;
3054 }
3055 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003056 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3057
Christopher Tate6ee412d2010-05-28 12:01:56 -07003058 if (clearTraces && tracesFile.exists()) tracesFile.delete();
Dan Egnor42471dd2010-01-07 17:25:22 -08003059 tracesFile.createNewFile();
3060 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3061 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003062 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e);
Dan Egnor42471dd2010-01-07 17:25:22 -08003063 return null;
3064 }
3065
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003066 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003067 return tracesFile;
3068 }
3069
3070 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids,
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003071 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003072 // Use a FileObserver to detect when traces finish writing.
3073 // The order of traces is considered important to maintain for legibility.
3074 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) {
3075 public synchronized void onEvent(int event, String path) { notify(); }
3076 };
3077
3078 try {
3079 observer.startWatching();
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003080
3081 // First collect all of the stacks of the most important pids.
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003082 if (firstPids != null) {
3083 try {
3084 int num = firstPids.size();
3085 for (int i = 0; i < num; i++) {
3086 synchronized (observer) {
3087 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT);
3088 observer.wait(200); // Wait for write-close, give up after 200msec
3089 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003090 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003091 } catch (InterruptedException e) {
3092 Log.wtf(TAG, e);
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003093 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003094 }
3095
3096 // Next measure CPU usage.
3097 if (processStats != null) {
3098 processStats.init();
3099 System.gc();
3100 processStats.update();
3101 try {
3102 synchronized (processStats) {
3103 processStats.wait(500); // measure over 1/2 second.
3104 }
3105 } catch (InterruptedException e) {
3106 }
3107 processStats.update();
3108
3109 // We'll take the stack crawls of just the top apps using CPU.
3110 final int N = processStats.countWorkingStats();
3111 int numProcs = 0;
3112 for (int i=0; i<N && numProcs<5; i++) {
3113 ProcessStats.Stats stats = processStats.getWorkingStats(i);
3114 if (lastPids.indexOfKey(stats.pid) >= 0) {
3115 numProcs++;
3116 try {
3117 synchronized (observer) {
3118 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT);
3119 observer.wait(200); // Wait for write-close, give up after 200msec
3120 }
3121 } catch (InterruptedException e) {
3122 Log.wtf(TAG, e);
3123 }
3124
3125 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003126 }
3127 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003128
Dan Egnor42471dd2010-01-07 17:25:22 -08003129 } finally {
3130 observer.stopWatching();
3131 }
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003132
3133 if (nativeProcs != null) {
3134 int[] pids = Process.getPidsForCommands(nativeProcs);
3135 if (pids != null) {
3136 for (int pid : pids) {
3137 Debug.dumpNativeBacktraceToFile(pid, tracesPath);
3138 }
3139 }
3140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 }
3142
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003143 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) {
Dianne Hackborn69dc66e2012-03-26 10:50:54 -07003144 if (true || IS_USER_BUILD) {
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003145 return;
3146 }
3147 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null);
3148 if (tracesPath == null || tracesPath.length() == 0) {
3149 return;
3150 }
3151
3152 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
3153 StrictMode.allowThreadDiskWrites();
3154 try {
3155 final File tracesFile = new File(tracesPath);
3156 final File tracesDir = tracesFile.getParentFile();
3157 final File tracesTmp = new File(tracesDir, "__tmp__");
3158 try {
rpcraigec7ed14c2012-07-25 13:10:37 -04003159 if (!tracesDir.exists()) {
3160 tracesFile.mkdirs();
3161 if (!SELinux.restorecon(tracesDir.getPath())) {
3162 return;
3163 }
3164 }
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003165 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x
3166
3167 if (tracesFile.exists()) {
3168 tracesTmp.delete();
3169 tracesFile.renameTo(tracesTmp);
3170 }
3171 StringBuilder sb = new StringBuilder();
3172 Time tobj = new Time();
3173 tobj.set(System.currentTimeMillis());
3174 sb.append(tobj.format("%Y-%m-%d %H:%M:%S"));
3175 sb.append(": ");
3176 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb);
3177 sb.append(" since ");
3178 sb.append(msg);
3179 FileOutputStream fos = new FileOutputStream(tracesFile);
3180 fos.write(sb.toString().getBytes());
3181 if (app == null) {
3182 fos.write("\n*** No application process!".getBytes());
3183 }
3184 fos.close();
3185 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw-
3186 } catch (IOException e) {
3187 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e);
3188 return;
3189 }
3190
3191 if (app != null) {
3192 ArrayList<Integer> firstPids = new ArrayList<Integer>();
3193 firstPids.add(app.pid);
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003194 dumpStackTraces(tracesPath, firstPids, null, null, null);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003195 }
3196
3197 File lastTracesFile = null;
3198 File curTracesFile = null;
3199 for (int i=9; i>=0; i--) {
3200 String name = String.format("slow%02d.txt", i);
3201 curTracesFile = new File(tracesDir, name);
3202 if (curTracesFile.exists()) {
3203 if (lastTracesFile != null) {
3204 curTracesFile.renameTo(lastTracesFile);
3205 } else {
3206 curTracesFile.delete();
3207 }
3208 }
3209 lastTracesFile = curTracesFile;
3210 }
3211 tracesFile.renameTo(curTracesFile);
3212 if (tracesTmp.exists()) {
3213 tracesTmp.renameTo(tracesFile);
3214 }
3215 } finally {
3216 StrictMode.setThreadPolicy(oldPolicy);
3217 }
3218 }
3219
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003220 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
3221 ActivityRecord parent, final String annotation) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003222 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
3223 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
3224
Dianne Hackborn287952c2010-09-22 22:34:31 -07003225 if (mController != null) {
3226 try {
3227 // 0 == continue, -1 = kill process immediately
3228 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation);
3229 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3230 } catch (RemoteException e) {
3231 mController = null;
3232 }
3233 }
3234
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003235 long anrTime = SystemClock.uptimeMillis();
3236 if (MONITOR_CPU_USAGE) {
3237 updateCpuStatsNow();
3238 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003239
3240 synchronized (this) {
3241 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
3242 if (mShuttingDown) {
3243 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
3244 return;
3245 } else if (app.notResponding) {
3246 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
3247 return;
3248 } else if (app.crashing) {
3249 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
3250 return;
3251 }
3252
3253 // In case we come through here for the same app before completing
3254 // this one, mark as anring now so we will bail out.
3255 app.notResponding = true;
Dan Egnor42471dd2010-01-07 17:25:22 -08003256
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003257 // Log the ANR to the event log.
3258 EventLog.writeEvent(EventLogTags.AM_ANR, app.pid, app.processName, app.info.flags,
3259 annotation);
Dan Egnor42471dd2010-01-07 17:25:22 -08003260
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003261 // Dump thread traces as quickly as we can, starting with "interesting" processes.
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003262 firstPids.add(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003263
3264 int parentPid = app.pid;
3265 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003266 if (parentPid != app.pid) firstPids.add(parentPid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003267
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003268 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Dan Egnor42471dd2010-01-07 17:25:22 -08003269
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003270 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
3271 ProcessRecord r = mLruProcesses.get(i);
3272 if (r != null && r.thread != null) {
3273 int pid = r.pid;
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003274 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
3275 if (r.persistent) {
3276 firstPids.add(pid);
3277 } else {
3278 lastPids.put(pid, Boolean.TRUE);
3279 }
3280 }
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003281 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 }
3283 }
3284
Dan Egnor42471dd2010-01-07 17:25:22 -08003285 // Log the ANR to the main log.
Jeff Browndeb6ed82012-04-10 14:26:26 -07003286 StringBuilder info = new StringBuilder();
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07003287 info.setLength(0);
Dan Egnor42471dd2010-01-07 17:25:22 -08003288 info.append("ANR in ").append(app.processName);
3289 if (activity != null && activity.shortComponentName != null) {
3290 info.append(" (").append(activity.shortComponentName).append(")");
Dianne Hackborn82e1ee92009-08-11 18:56:41 -07003291 }
Eric Rowe6f4f6192010-02-17 18:29:04 -08003292 info.append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 if (annotation != null) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003294 info.append("Reason: ").append(annotation).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003295 }
Dan Egnor42471dd2010-01-07 17:25:22 -08003296 if (parent != null && parent != activity) {
Eric Rowe6f4f6192010-02-17 18:29:04 -08003297 info.append("Parent: ").append(parent.shortComponentName).append("\n");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299
Dianne Hackborn287952c2010-09-22 22:34:31 -07003300 final ProcessStats processStats = new ProcessStats(true);
3301
Dianne Hackbornf72467a2012-06-08 17:23:59 -07003302 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07003303
Dan Egnor42471dd2010-01-07 17:25:22 -08003304 String cpuInfo = null;
3305 if (MONITOR_CPU_USAGE) {
3306 updateCpuStatsNow();
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003307 synchronized (mProcessStatsThread) {
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003308 cpuInfo = mProcessStats.printCurrentState(anrTime);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003309 }
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003310 info.append(processStats.printCurrentLoad());
Dan Egnor42471dd2010-01-07 17:25:22 -08003311 info.append(cpuInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 }
3313
Dianne Hackborn6b1afeb2010-08-31 15:40:21 -07003314 info.append(processStats.printCurrentState(anrTime));
3315
Joe Onorato8a9b2202010-02-26 18:56:32 -08003316 Slog.e(TAG, info.toString());
Dan Egnor42471dd2010-01-07 17:25:22 -08003317 if (tracesFile == null) {
3318 // There is no trace file, so dump (only) the alleged culprit's threads to the log
3319 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
3320 }
3321
Jeff Sharkeya353d262011-10-28 11:12:06 -07003322 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
3323 cpuInfo, tracesFile, null);
Dan Egnor42471dd2010-01-07 17:25:22 -08003324
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003325 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 try {
Dan Egnor42471dd2010-01-07 17:25:22 -08003327 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
3328 int res = mController.appNotResponding(app.processName, app.pid, info.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 if (res != 0) {
Dan Egnor42471dd2010-01-07 17:25:22 -08003330 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid);
3331 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 }
3333 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07003334 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 }
3336 }
3337
Dan Egnor42471dd2010-01-07 17:25:22 -08003338 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
3339 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
3340 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003341
3342 synchronized (this) {
3343 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003344 Slog.w(TAG, "Killing " + app + ": background ANR");
3345 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
3346 app.processName, app.setAdj, "background ANR");
3347 Process.killProcessQuiet(app.pid);
Dianne Hackbornad5499d2010-03-29 18:08:45 -07003348 return;
3349 }
3350
3351 // Set the app's notResponding state, and look up the errorReportReceiver
3352 makeAppNotRespondingLocked(app,
3353 activity != null ? activity.shortComponentName : null,
3354 annotation != null ? "ANR " + annotation : "ANR",
3355 info.toString());
3356
3357 // Bring up the infamous App Not Responding dialog
3358 Message msg = Message.obtain();
3359 HashMap map = new HashMap();
3360 msg.what = SHOW_NOT_RESPONDING_MSG;
3361 msg.obj = map;
3362 map.put("app", app);
3363 if (activity != null) {
3364 map.put("activity", activity);
3365 }
3366
3367 mHandler.sendMessage(msg);
Dan Egnor42471dd2010-01-07 17:25:22 -08003368 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 }
3370
Dianne Hackborn0dad3642010-09-09 21:25:35 -07003371 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) {
3372 if (!mLaunchWarningShown) {
3373 mLaunchWarningShown = true;
3374 mHandler.post(new Runnable() {
3375 @Override
3376 public void run() {
3377 synchronized (ActivityManagerService.this) {
3378 final Dialog d = new LaunchWarningWindow(mContext, cur, next);
3379 d.show();
3380 mHandler.postDelayed(new Runnable() {
3381 @Override
3382 public void run() {
3383 synchronized (ActivityManagerService.this) {
3384 d.dismiss();
3385 mLaunchWarningShown = false;
3386 }
3387 }
3388 }, 4000);
3389 }
3390 }
3391 });
3392 }
3393 }
3394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003395 public boolean clearApplicationUserData(final String packageName,
Amith Yamasani742a6712011-05-04 14:49:28 -07003396 final IPackageDataObserver observer, final int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003397 enforceNotIsolatedCaller("clearApplicationUserData");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 int uid = Binder.getCallingUid();
3399 int pid = Binder.getCallingPid();
3400 long callingId = Binder.clearCallingIdentity();
3401 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003402 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 int pkgUid = -1;
3404 synchronized(this) {
3405 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003406 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 } catch (RemoteException e) {
3408 }
3409 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003410 Slog.w(TAG, "Invalid packageName:" + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 return false;
3412 }
3413 if (uid == pkgUid || checkComponentPermission(
3414 android.Manifest.permission.CLEAR_APP_USER_DATA,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08003415 pid, uid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003417 forceStopPackageLocked(packageName, pkgUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 } else {
3419 throw new SecurityException(pid+" does not have permission:"+
3420 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" +
3421 "for process:"+packageName);
3422 }
3423 }
3424
3425 try {
3426 //clear application user data
Amith Yamasani483f3b02012-03-13 16:08:00 -07003427 pm.clearApplicationUserData(packageName, observer, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED,
3429 Uri.fromParts("package", packageName, null));
3430 intent.putExtra(Intent.EXTRA_UID, pkgUid);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003431 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent,
Amith Yamasani742a6712011-05-04 14:49:28 -07003432 null, null, 0, null, null, null, false, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 } catch (RemoteException e) {
3434 }
3435 } finally {
3436 Binder.restoreCallingIdentity(callingId);
3437 }
3438 return true;
3439 }
3440
Dianne Hackborn03abb812010-01-04 18:43:19 -08003441 public void killBackgroundProcesses(final String packageName) {
3442 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3443 != PackageManager.PERMISSION_GRANTED &&
3444 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES)
3445 != PackageManager.PERMISSION_GRANTED) {
3446 String msg = "Permission Denial: killBackgroundProcesses() from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 + Binder.getCallingPid()
3448 + ", uid=" + Binder.getCallingUid()
Dianne Hackborn03abb812010-01-04 18:43:19 -08003449 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003450 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 throw new SecurityException(msg);
3452 }
3453
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003454 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455 long callingId = Binder.clearCallingIdentity();
3456 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003457 IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 int pkgUid = -1;
3459 synchronized(this) {
3460 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003461 pkgUid = pm.getPackageUid(packageName, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 } catch (RemoteException e) {
3463 }
3464 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003465 Slog.w(TAG, "Invalid packageName: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 return;
3467 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003468 killPackageProcessesLocked(packageName, pkgUid, -1,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003469 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background");
3470 }
3471 } finally {
3472 Binder.restoreCallingIdentity(callingId);
3473 }
3474 }
3475
3476 public void killAllBackgroundProcesses() {
3477 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES)
3478 != PackageManager.PERMISSION_GRANTED) {
3479 String msg = "Permission Denial: killAllBackgroundProcesses() from pid="
3480 + Binder.getCallingPid()
3481 + ", uid=" + Binder.getCallingUid()
3482 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES;
3483 Slog.w(TAG, msg);
3484 throw new SecurityException(msg);
3485 }
3486
3487 long callingId = Binder.clearCallingIdentity();
3488 try {
3489 synchronized(this) {
3490 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
3491 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3492 final int NA = apps.size();
3493 for (int ia=0; ia<NA; ia++) {
3494 ProcessRecord app = apps.valueAt(ia);
3495 if (app.persistent) {
3496 // we don't kill persistent processes
3497 continue;
3498 }
3499 if (app.removed) {
3500 procs.add(app);
3501 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
3502 app.removed = true;
3503 procs.add(app);
3504 }
3505 }
3506 }
3507
3508 int N = procs.size();
3509 for (int i=0; i<N; i++) {
3510 removeProcessLocked(procs.get(i), false, true, "kill all background");
3511 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003512 }
3513 } finally {
3514 Binder.restoreCallingIdentity(callingId);
3515 }
3516 }
3517
3518 public void forceStopPackage(final String packageName) {
3519 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
3520 != PackageManager.PERMISSION_GRANTED) {
3521 String msg = "Permission Denial: forceStopPackage() from pid="
3522 + Binder.getCallingPid()
3523 + ", uid=" + Binder.getCallingUid()
3524 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003525 Slog.w(TAG, msg);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003526 throw new SecurityException(msg);
3527 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003528 final int userId = UserHandle.getCallingUserId();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003529 long callingId = Binder.clearCallingIdentity();
3530 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07003531 IPackageManager pm = AppGlobals.getPackageManager();
Dianne Hackborn03abb812010-01-04 18:43:19 -08003532 int pkgUid = -1;
3533 synchronized(this) {
3534 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003535 pkgUid = pm.getPackageUid(packageName, userId);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003536 } catch (RemoteException e) {
3537 }
3538 if (pkgUid == -1) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003539 Slog.w(TAG, "Invalid packageName: " + packageName);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003540 return;
3541 }
3542 forceStopPackageLocked(packageName, pkgUid);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003543 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003544 pm.setPackageStoppedState(packageName, true, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003545 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08003546 } catch (IllegalArgumentException e) {
3547 Slog.w(TAG, "Failed trying to unstop package "
3548 + packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08003549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 }
3551 } finally {
3552 Binder.restoreCallingIdentity(callingId);
3553 }
3554 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003555
3556 /*
3557 * The pkg name and uid have to be specified.
3558 * @see android.app.IActivityManager#killApplicationWithUid(java.lang.String, int)
3559 */
3560 public void killApplicationWithUid(String pkg, int uid) {
3561 if (pkg == null) {
3562 return;
3563 }
3564 // Make sure the uid is valid.
3565 if (uid < 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003566 Slog.w(TAG, "Invalid uid specified for pkg : " + pkg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003567 return;
3568 }
3569 int callerUid = Binder.getCallingUid();
3570 // Only the system server can kill an application
3571 if (callerUid == Process.SYSTEM_UID) {
Suchi Amalapurapud9d25762009-08-17 16:57:03 -07003572 // Post an aysnc message to kill the application
3573 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG);
3574 msg.arg1 = uid;
3575 msg.arg2 = 0;
3576 msg.obj = pkg;
Suchi Amalapurapud50066f2009-08-18 16:57:41 -07003577 mHandler.sendMessage(msg);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003578 } else {
3579 throw new SecurityException(callerUid + " cannot kill pkg: " +
3580 pkg);
3581 }
3582 }
3583
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003584 public void closeSystemDialogs(String reason) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003585 enforceNotIsolatedCaller("closeSystemDialogs");
Dianne Hackborne302a162012-05-15 14:58:32 -07003586
3587 final int uid = Binder.getCallingUid();
3588 final long origId = Binder.clearCallingIdentity();
3589 synchronized (this) {
3590 closeSystemDialogsLocked(uid, reason);
3591 }
3592 Binder.restoreCallingIdentity(origId);
3593 }
3594
3595 void closeSystemDialogsLocked(int callingUid, String reason) {
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003596 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003597 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003598 if (reason != null) {
3599 intent.putExtra("reason", reason);
3600 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003601 mWindowManager.closeSystemDialogs(reason);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003602
Dianne Hackborne302a162012-05-15 14:58:32 -07003603 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
3604 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn1927ae82012-06-22 15:21:36 -07003605 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
Dianne Hackborne302a162012-05-15 14:58:32 -07003606 r.stack.finishActivityLocked(r, i,
3607 Activity.RESULT_CANCELED, null, "close-sys");
Dianne Hackbornffa42482009-09-23 22:20:11 -07003608 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003609 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003610
3611 final long origId = Binder.clearCallingIdentity();
3612 try {
3613 broadcastIntentLocked(null, null, intent, null,
3614 null, 0, null, null, null, false, false, -1,
3615 callingUid, UserHandle.USER_ALL);
3616 } finally {
3617 Binder.restoreCallingIdentity(origId);
3618 }
Dianne Hackborna6ddc8a2009-07-28 17:49:55 -07003619 }
Dianne Hackborne302a162012-05-15 14:58:32 -07003620
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003621 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids)
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003622 throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003623 enforceNotIsolatedCaller("getProcessMemoryInfo");
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003624 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length];
3625 for (int i=pids.length-1; i>=0; i--) {
3626 infos[i] = new Debug.MemoryInfo();
3627 Debug.getMemoryInfo(pids[i], infos[i]);
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003628 }
Dianne Hackborn4f21c4c2009-09-17 10:24:05 -07003629 return infos;
Dianne Hackborn3025ef32009-08-31 21:31:47 -07003630 }
Christopher Tate5e1ab332009-09-01 20:32:49 -07003631
Dianne Hackbornb437e092011-08-05 17:50:29 -07003632 public long[] getProcessPss(int[] pids) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08003633 enforceNotIsolatedCaller("getProcessPss");
Dianne Hackbornb437e092011-08-05 17:50:29 -07003634 long[] pss = new long[pids.length];
3635 for (int i=pids.length-1; i>=0; i--) {
3636 pss[i] = Debug.getPss(pids[i]);
3637 }
3638 return pss;
3639 }
3640
Christopher Tate5e1ab332009-09-01 20:32:49 -07003641 public void killApplicationProcess(String processName, int uid) {
3642 if (processName == null) {
3643 return;
3644 }
3645
3646 int callerUid = Binder.getCallingUid();
3647 // Only the system server can kill an application
3648 if (callerUid == Process.SYSTEM_UID) {
3649 synchronized (this) {
3650 ProcessRecord app = getProcessRecordLocked(processName, uid);
Christopher Tate4a627c72011-04-01 14:43:32 -07003651 if (app != null && app.thread != null) {
Christopher Tate5e1ab332009-09-01 20:32:49 -07003652 try {
3653 app.thread.scheduleSuicide();
3654 } catch (RemoteException e) {
3655 // If the other end already died, then our work here is done.
3656 }
3657 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003658 Slog.w(TAG, "Process/uid not found attempting kill of "
Christopher Tate5e1ab332009-09-01 20:32:49 -07003659 + processName + " / " + uid);
3660 }
3661 }
3662 } else {
3663 throw new SecurityException(callerUid + " cannot kill app process: " +
3664 processName);
3665 }
3666 }
3667
Dianne Hackborn03abb812010-01-04 18:43:19 -08003668 private void forceStopPackageLocked(final String packageName, int uid) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003669 forceStopPackageLocked(packageName, uid, false, false, true, false,
3670 UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003671 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED,
3672 Uri.fromParts("package", packageName, null));
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07003673 if (!mProcessesReady) {
3674 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 intent.putExtra(Intent.EXTRA_UID, uid);
3677 broadcastIntentLocked(null, null, intent,
3678 null, null, 0, null, null, null,
Amith Yamasani742a6712011-05-04 14:49:28 -07003679 false, false,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07003680 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003681 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003682
3683 private void forceStopUserLocked(int userId) {
3684 forceStopPackageLocked(null, -1, false, false, true, false, userId);
3685 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
3686 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3687 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3688 broadcastIntentLocked(null, null, intent,
3689 null, null, 0, null, null, null,
3690 false, false,
3691 MY_PID, Process.SYSTEM_UID, userId);
3692 }
3693
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003694 private final boolean killPackageProcessesLocked(String packageName, int uid,
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003695 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart,
3696 boolean doit, boolean evenPersistent, String reason) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003697 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698
Dianne Hackborn03abb812010-01-04 18:43:19 -08003699 // Remove all processes this package may have touched: all with the
3700 // same UID (except for the system or root user), and all whose name
3701 // matches the package name.
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003702 final String procNamePrefix = packageName != null ? (packageName + ":") : null;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003703 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
3704 final int NA = apps.size();
3705 for (int ia=0; ia<NA; ia++) {
3706 ProcessRecord app = apps.valueAt(ia);
Christopher Tate3dacd842011-08-19 14:56:15 -07003707 if (app.persistent && !evenPersistent) {
Christopher Tate064d8422011-07-26 15:38:07 -07003708 // we don't kill persistent processes
3709 continue;
3710 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003711 if (app.removed) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003712 if (doit) {
3713 procs.add(app);
3714 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003715 // If no package is specified, we call all processes under the
3716 // give user id.
3717 } else if (packageName == null) {
3718 if (app.userId == userId) {
3719 if (app.setAdj >= minOomAdj) {
3720 if (!doit) {
3721 return true;
3722 }
3723 app.removed = true;
3724 procs.add(app);
3725 }
3726 }
Amith Yamasani13593602012-03-22 16:16:17 -07003727 // If uid is specified and the uid and process name match
3728 // Or, the uid is not specified and the process name matches
3729 } else if (((uid > 0 && uid != Process.SYSTEM_UID && app.info.uid == uid)
Amith Yamasani34db3d62012-04-02 16:35:19 -07003730 || ((app.processName.equals(packageName)
3731 || app.processName.startsWith(procNamePrefix))
3732 && uid < 0))) {
Dianne Hackborn03abb812010-01-04 18:43:19 -08003733 if (app.setAdj >= minOomAdj) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003734 if (!doit) {
3735 return true;
3736 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003737 app.removed = true;
3738 procs.add(app);
3739 }
3740 }
3741 }
3742 }
3743
3744 int N = procs.size();
3745 for (int i=0; i<N; i++) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003746 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason);
Dianne Hackborn03abb812010-01-04 18:43:19 -08003747 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003748 return N > 0;
Dianne Hackborn03abb812010-01-04 18:43:19 -08003749 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003750
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003751 private final boolean forceStopPackageLocked(String name, int uid,
Christopher Tate3dacd842011-08-19 14:56:15 -07003752 boolean callerWillRestart, boolean purgeCache, boolean doit,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003753 boolean evenPersistent, int userId) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003754 int i;
3755 int N;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003756
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003757 if (uid < 0 && name != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 try {
Amith Yamasani483f3b02012-03-13 16:08:00 -07003759 uid = AppGlobals.getPackageManager().getPackageUid(name, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 } catch (RemoteException e) {
3761 }
3762 }
3763
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003764 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003765 if (name != null) {
3766 Slog.i(TAG, "Force stopping package " + name + " uid=" + uid);
3767 } else {
3768 Slog.i(TAG, "Force stopping user " + userId);
3769 }
Dianne Hackborn03abb812010-01-04 18:43:19 -08003770
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003771 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator();
3772 while (badApps.hasNext()) {
3773 SparseArray<Long> ba = badApps.next();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003774 for (i=ba.size()-1; i>=0; i--) {
3775 boolean remove = false;
3776 final int entUid = ba.keyAt(i);
3777 if (name != null) {
3778 if (entUid == uid) {
3779 remove = true;
3780 }
3781 } else if (UserHandle.getUserId(entUid) == userId) {
3782 remove = true;
3783 }
3784 if (remove) {
3785 ba.removeAt(i);
3786 }
3787 }
3788 if (ba.size() == 0) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003789 badApps.remove();
3790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003791 }
3792 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003793
3794 boolean didSomething = killPackageProcessesLocked(name, uid,
3795 name == null ? userId : -1 , -100, callerWillRestart, false,
3796 doit, evenPersistent,
3797 name == null ? ("force stop user " + userId) : ("force stop " + name));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003799 TaskRecord lastTask = null;
3800 for (i=0; i<mMainStack.mHistory.size(); i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003801 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003802 final boolean samePackage = r.packageName.equals(name)
3803 || (name == null && r.userId == userId);
Amith Yamasani13593602012-03-22 16:16:17 -07003804 if (r.userId == userId
3805 && (samePackage || r.task == lastTask)
Christopher Tate3dacd842011-08-19 14:56:15 -07003806 && (r.app == null || evenPersistent || !r.app.persistent)) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003807 if (!doit) {
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003808 if (r.finishing) {
3809 // If this activity is just finishing, then it is not
3810 // interesting as far as something to stop.
3811 continue;
3812 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003813 return true;
3814 }
3815 didSomething = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003816 Slog.i(TAG, " Force finishing activity " + r);
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003817 if (samePackage) {
3818 if (r.app != null) {
3819 r.app.removed = true;
3820 }
3821 r.app = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822 }
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003823 lastTask = r.task;
3824 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003825 null, "force-stop", true)) {
Dianne Hackborne5ba16a2011-09-09 12:35:29 -07003826 i--;
3827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828 }
3829 }
3830
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003831 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) {
3832 if (!doit) {
3833 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003835 didSomething = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003837
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07003838 if (name == null) {
3839 // Remove all sticky broadcasts from this user.
3840 mStickyBroadcasts.remove(userId);
3841 }
3842
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003843 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>();
Amith Yamasani13593602012-03-22 16:16:17 -07003844 for (ContentProviderRecord provider : mProviderMap.getProvidersByClass(userId).values()) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003845 if ((name == null || provider.info.packageName.equals(name))
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003846 && (provider.proc == null || evenPersistent || !provider.proc.persistent)) {
3847 if (!doit) {
3848 return true;
3849 }
3850 didSomething = true;
3851 providers.add(provider);
3852 }
3853 }
3854
3855 N = providers.size();
3856 for (i=0; i<N; i++) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07003857 removeDyingProviderLocked(null, providers.get(i), true);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07003858 }
3859
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003860 if (doit) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003861 if (purgeCache && name != null) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003862 AttributeCache ac = AttributeCache.instance();
3863 if (ac != null) {
3864 ac.removePackage(name);
3865 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003866 }
Dianne Hackborn38cc8962011-10-13 11:33:55 -07003867 if (mBooted) {
3868 mMainStack.resumeTopActivityLocked(null);
3869 mMainStack.scheduleIdleLocked();
3870 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003871 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003872
3873 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 }
3875
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003876 private final boolean removeProcessLocked(ProcessRecord app,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003877 boolean callerWillRestart, boolean allowRestart, String reason) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003878 final String name = app.processName;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003879 final int uid = app.uid;
Joe Onorato8a9b2202010-02-26 18:56:32 -08003880 if (DEBUG_PROCESSES) Slog.d(
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003881 TAG, "Force removing proc " + app.toShortString() + " (" + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 + "/" + uid + ")");
3883
3884 mProcessNames.remove(name, uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003885 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003886 if (mHeavyWeightProcess == app) {
3887 mHeavyWeightProcess = null;
3888 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3889 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 boolean needRestart = false;
3891 if (app.pid > 0 && app.pid != MY_PID) {
3892 int pid = app.pid;
3893 synchronized (mPidsSelfLocked) {
3894 mPidsSelfLocked.remove(pid);
3895 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
3896 }
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003897 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason);
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003898 handleAppDiedLocked(app, true, allowRestart);
Dianne Hackborndd71fc82009-12-16 19:24:32 -08003899 mLruProcesses.remove(app);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08003900 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003902 if (app.persistent && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 if (!callerWillRestart) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003904 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 } else {
3906 needRestart = true;
3907 }
3908 }
3909 } else {
3910 mRemovedProcesses.add(app);
3911 }
3912
3913 return needRestart;
3914 }
3915
3916 private final void processStartTimedOutLocked(ProcessRecord app) {
3917 final int pid = app.pid;
3918 boolean gone = false;
3919 synchronized (mPidsSelfLocked) {
3920 ProcessRecord knownApp = mPidsSelfLocked.get(pid);
3921 if (knownApp != null && knownApp.thread == null) {
3922 mPidsSelfLocked.remove(pid);
3923 gone = true;
3924 }
3925 }
3926
3927 if (gone) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003928 Slog.w(TAG, "Process " + app + " failed to attach");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003929 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, pid, app.uid,
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003930 app.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08003931 mProcessNames.remove(app.processName, app.uid);
3932 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -07003933 if (mHeavyWeightProcess == app) {
3934 mHeavyWeightProcess = null;
3935 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
3936 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003937 // Take care of any launching providers waiting for this process.
3938 checkAppInLaunchingProvidersLocked(app, true);
3939 // Take care of any services that are waiting for the process.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003940 mServices.processStartTimedOutLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003941 EventLog.writeEvent(EventLogTags.AM_KILL, pid,
3942 app.processName, app.setAdj, "start timeout");
3943 Process.killProcessQuiet(pid);
Christopher Tate181fafa2009-05-14 11:12:14 -07003944 if (mBackupTarget != null && mBackupTarget.app.pid == pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003945 Slog.w(TAG, "Unattached app died before backup, skipping");
Christopher Tate181fafa2009-05-14 11:12:14 -07003946 try {
3947 IBackupManager bm = IBackupManager.Stub.asInterface(
3948 ServiceManager.getService(Context.BACKUP_SERVICE));
3949 bm.agentDisconnected(app.info.packageName);
3950 } catch (RemoteException e) {
3951 // Can't happen; the backup manager is local
3952 }
3953 }
Christopher Tatef46723b2012-01-26 14:19:24 -08003954 if (isPendingBroadcastProcessLocked(pid)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003955 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
Christopher Tatef46723b2012-01-26 14:19:24 -08003956 skipPendingBroadcastLocked(pid);
Dianne Hackbornf670ef72009-11-16 13:59:16 -08003957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003959 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 }
3961 }
3962
3963 private final boolean attachApplicationLocked(IApplicationThread thread,
3964 int pid) {
3965
3966 // Find the application record that is being attached... either via
3967 // the pid if we are running in multiple processes, or just pull the
3968 // next app record if we are emulating process with anonymous threads.
3969 ProcessRecord app;
3970 if (pid != MY_PID && pid >= 0) {
3971 synchronized (mPidsSelfLocked) {
3972 app = mPidsSelfLocked.get(pid);
3973 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 } else {
3975 app = null;
3976 }
3977
3978 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003979 Slog.w(TAG, "No pending application record for pid " + pid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 + " (IApplicationThread " + thread + "); dropping process");
Doug Zongker2bec3d42009-12-04 12:52:44 -08003981 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 if (pid > 0 && pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003983 Process.killProcessQuiet(pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 } else {
3985 try {
3986 thread.scheduleExit();
3987 } catch (Exception e) {
3988 // Ignore exceptions.
3989 }
3990 }
3991 return false;
3992 }
3993
3994 // If this application record is still attached to a previous
3995 // process, clean it up now.
3996 if (app.thread != null) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -07003997 handleAppDiedLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003998 }
3999
4000 // Tell the process all about itself.
4001
Joe Onorato8a9b2202010-02-26 18:56:32 -08004002 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 TAG, "Binding process pid " + pid + " to record " + app);
4004
4005 String processName = app.processName;
4006 try {
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004007 AppDeathRecipient adr = new AppDeathRecipient(
4008 app, pid, thread);
4009 thread.asBinder().linkToDeath(adr, 0);
4010 app.deathRecipient = adr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 } catch (RemoteException e) {
4012 app.resetPackageList();
4013 startProcessLocked(app, "link fail", processName);
4014 return false;
4015 }
4016
Doug Zongker2bec3d42009-12-04 12:52:44 -08004017 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.pid, app.processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018
4019 app.thread = thread;
4020 app.curAdj = app.setAdj = -100;
Dianne Hackborn09c916b2009-12-08 14:50:51 -08004021 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
4022 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 app.forcingToForeground = null;
4024 app.foregroundServices = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -07004025 app.hasShownUi = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 app.debugging = false;
4027
4028 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
4029
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004030 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004031 List providers = normalMode ? generateApplicationProvidersLocked(app) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004033 if (!normalMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004034 Slog.i(TAG, "Launching preboot mode app: " + app);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004035 }
4036
Joe Onorato8a9b2202010-02-26 18:56:32 -08004037 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 TAG, "New app record " + app
4039 + " thread=" + thread.asBinder() + " pid=" + pid);
4040 try {
4041 int testMode = IApplicationThread.DEBUG_OFF;
4042 if (mDebugApp != null && mDebugApp.equals(processName)) {
4043 testMode = mWaitForDebugger
4044 ? IApplicationThread.DEBUG_WAIT
4045 : IApplicationThread.DEBUG_ON;
4046 app.debugging = true;
4047 if (mDebugTransient) {
4048 mDebugApp = mOrigDebugApp;
4049 mWaitForDebugger = mOrigWaitForDebugger;
4050 }
4051 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004052 String profileFile = app.instrumentationProfileFile;
4053 ParcelFileDescriptor profileFd = null;
4054 boolean profileAutoStop = false;
4055 if (mProfileApp != null && mProfileApp.equals(processName)) {
4056 mProfileProc = app;
4057 profileFile = mProfileFile;
4058 profileFd = mProfileFd;
4059 profileAutoStop = mAutoStopProfiler;
4060 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08004061 boolean enableOpenGlTrace = false;
4062 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) {
4063 enableOpenGlTrace = true;
4064 mOpenGlTraceApp = null;
4065 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004066
Christopher Tate181fafa2009-05-14 11:12:14 -07004067 // If the app is being launched for restore or full backup, set it up specially
4068 boolean isRestrictedBackupMode = false;
4069 if (mBackupTarget != null && mBackupAppName.equals(processName)) {
4070 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE)
Christopher Tate75a99702011-05-18 16:28:19 -07004071 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL)
Christopher Tate181fafa2009-05-14 11:12:14 -07004072 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL);
4073 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004074
Dianne Hackbornd7f6daa2009-06-22 17:06:35 -07004075 ensurePackageDexOpt(app.instrumentationInfo != null
4076 ? app.instrumentationInfo.packageName
4077 : app.info.packageName);
4078 if (app.instrumentationClass != null) {
4079 ensurePackageDexOpt(app.instrumentationClass.getPackageName());
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004080 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08004081 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -07004082 + processName + " with config " + mConfiguration);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004083 ApplicationInfo appInfo = app.instrumentationInfo != null
4084 ? app.instrumentationInfo : app.info;
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -07004085 app.compat = compatibilityInfoForPackageLocked(appInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004086 if (profileFd != null) {
4087 profileFd = profileFd.dup();
4088 }
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004089 thread.bindApplication(processName, appInfo, providers,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004090 app.instrumentationClass, profileFile, profileFd, profileAutoStop,
Siva Velusamy92a8b222012-03-09 16:24:04 -08004091 app.instrumentationArguments, app.instrumentationWatcher, testMode,
4092 enableOpenGlTrace, isRestrictedBackupMode || !normalMode, app.persistent,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004093 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(),
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08004094 mCoreSettingsObserver.getCoreSettingsLocked());
Dianne Hackborndd71fc82009-12-16 19:24:32 -08004095 updateLruProcessLocked(app, false, true);
Dianne Hackbornfd12af42009-08-27 00:44:33 -07004096 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 } catch (Exception e) {
4098 // todo: Yikes! What should we do? For now we will try to
4099 // start another process, but that could easily get us in
4100 // an infinite loop of restarting processes...
Joe Onorato8a9b2202010-02-26 18:56:32 -08004101 Slog.w(TAG, "Exception thrown during bind!", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102
4103 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -07004104 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 startProcessLocked(app, "bind fail", processName);
4106 return false;
4107 }
4108
4109 // Remove this record from the list of starting applications.
4110 mPersistentStartingProcesses.remove(app);
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004111 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
4112 "Attach application locked removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 mProcessesOnHold.remove(app);
4114
4115 boolean badApp = false;
4116 boolean didSomething = false;
4117
4118 // See if the top visible activity is waiting to run in this process...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004119 ActivityRecord hr = mMainStack.topRunningActivityLocked(null);
Christopher Tate04c0af82010-06-07 18:35:20 -07004120 if (hr != null && normalMode) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004121 if (hr.app == null && app.uid == hr.info.applicationInfo.uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 && processName.equals(hr.processName)) {
4123 try {
Mike Lockwood3a74bd32011-08-12 13:55:22 -07004124 if (mHeadless) {
4125 Slog.e(TAG, "Starting activities not supported on headless device: " + hr);
4126 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 didSomething = true;
4128 }
4129 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004130 Slog.w(TAG, "Exception in new application when starting activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004131 + hr.intent.getComponent().flattenToShortString(), e);
4132 badApp = true;
4133 }
4134 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004135 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 }
4137 }
4138
4139 // Find any services that should be running in this process...
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004140 if (!badApp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 try {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004142 didSomething |= mServices.attachApplicationLocked(app, processName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 } catch (Exception e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 badApp = true;
4145 }
4146 }
4147
Christopher Tatef46723b2012-01-26 14:19:24 -08004148 // Check if a next-broadcast receiver is in this process...
4149 if (!badApp && isPendingBroadcastProcessLocked(pid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 try {
Christopher Tatef46723b2012-01-26 14:19:24 -08004151 didSomething = sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004152 } catch (Exception e) {
Christopher Tatef46723b2012-01-26 14:19:24 -08004153 // If the app died trying to launch the receiver we declare it 'bad'
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154 badApp = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 }
4156 }
4157
Christopher Tate181fafa2009-05-14 11:12:14 -07004158 // Check whether the next backup agent is in this process...
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004159 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004160 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07004161 ensurePackageDexOpt(mBackupTarget.appInfo.packageName);
Christopher Tate181fafa2009-05-14 11:12:14 -07004162 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004163 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo,
4164 compatibilityInfoForPackageLocked(mBackupTarget.appInfo),
4165 mBackupTarget.backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -07004166 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004167 Slog.w(TAG, "Exception scheduling backup agent creation: ");
Christopher Tate181fafa2009-05-14 11:12:14 -07004168 e.printStackTrace();
4169 }
4170 }
4171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004172 if (badApp) {
4173 // todo: Also need to kill application to deal with all
4174 // kinds of exceptions.
Dianne Hackborn130b0d22011-07-26 22:07:48 -07004175 handleAppDiedLocked(app, false, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 return false;
4177 }
4178
4179 if (!didSomething) {
4180 updateOomAdjLocked();
4181 }
4182
4183 return true;
4184 }
4185
4186 public final void attachApplication(IApplicationThread thread) {
4187 synchronized (this) {
4188 int callingPid = Binder.getCallingPid();
4189 final long origId = Binder.clearCallingIdentity();
4190 attachApplicationLocked(thread, callingPid);
4191 Binder.restoreCallingIdentity(origId);
4192 }
4193 }
4194
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004195 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07004197 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config);
4198 if (stopProfiling) {
4199 synchronized (this) {
4200 if (mProfileProc == r.app) {
4201 if (mProfileFd != null) {
4202 try {
4203 mProfileFd.close();
4204 } catch (IOException e) {
4205 }
4206 clearProfilerLocked();
4207 }
4208 }
4209 }
4210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 Binder.restoreCallingIdentity(origId);
4212 }
4213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 void enableScreenAfterBoot() {
Doug Zongker2bec3d42009-12-04 12:52:44 -08004215 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN,
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004216 SystemClock.uptimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 mWindowManager.enableScreenAfterBoot();
Jeff Brownc042ee22012-05-08 13:03:42 -07004218
4219 synchronized (this) {
4220 updateEventDispatchingLocked();
4221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004222 }
4223
Dianne Hackborn661cd522011-08-22 00:26:20 -07004224 public void showBootMessage(final CharSequence msg, final boolean always) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004225 enforceNotIsolatedCaller("showBootMessage");
Dianne Hackborn661cd522011-08-22 00:26:20 -07004226 mWindowManager.showBootMessage(msg, always);
4227 }
4228
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004229 public void dismissKeyguardOnNextActivity() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004230 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity");
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004231 final long token = Binder.clearCallingIdentity();
4232 try {
4233 synchronized (this) {
4234 if (mLockScreenShown) {
4235 mLockScreenShown = false;
4236 comeOutOfSleepIfNeededLocked();
4237 }
4238 mMainStack.dismissKeyguardOnNextActivityLocked();
Dianne Hackborn1e88e982012-04-24 18:35:55 -07004239 }
Jeff Sharkey7ffaa982012-04-30 16:59:05 -07004240 } finally {
4241 Binder.restoreCallingIdentity(token);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004242 }
4243 }
4244
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004245 final void finishBooting() {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004246 IntentFilter pkgFilter = new IntentFilter();
4247 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
4248 pkgFilter.addDataScheme("package");
4249 mContext.registerReceiver(new BroadcastReceiver() {
4250 @Override
4251 public void onReceive(Context context, Intent intent) {
4252 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4253 if (pkgs != null) {
4254 for (String pkg : pkgs) {
Vairavan Srinivasan61f07652010-07-22 13:36:40 -07004255 synchronized (ActivityManagerService.this) {
Amith Yamasani483f3b02012-03-13 16:08:00 -07004256 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) {
4257 setResultCode(Activity.RESULT_OK);
4258 return;
4259 }
4260 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004261 }
4262 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004263 }
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004264 }, pkgFilter);
Amith Yamasani13593602012-03-22 16:16:17 -07004265
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004266 synchronized (this) {
4267 // Ensure that any processes we had put on hold are now started
4268 // up.
4269 final int NP = mProcessesOnHold.size();
4270 if (NP > 0) {
4271 ArrayList<ProcessRecord> procs =
4272 new ArrayList<ProcessRecord>(mProcessesOnHold);
4273 for (int ip=0; ip<NP; ip++) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07004274 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: "
4275 + procs.get(ip));
4276 startProcessLocked(procs.get(ip), "on-hold", null);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004277 }
4278 }
4279
4280 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07004281 // Start looking for apps that are abusing wake locks.
4282 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
Dianne Hackborn287952c2010-09-22 22:34:31 -07004283 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004284 // Tell anyone interested that we are done booting!
Dianne Hackbornf4c454b2010-08-11 12:47:41 -07004285 SystemProperties.set("sys.boot_completed", "1");
Guang Zhu191713a2012-01-12 12:02:22 -08004286 SystemProperties.set("dev.bootcomplete", "1");
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004287 for (int i=0; i<mStartedUsers.size(); i++) {
4288 UserStartedState uss = mStartedUsers.valueAt(i);
4289 if (uss.mState == UserStartedState.STATE_BOOTING) {
4290 uss.mState = UserStartedState.STATE_RUNNING;
4291 broadcastIntentLocked(null, null,
4292 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
4293 null, null, 0, null, null,
4294 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
4295 false, false, MY_PID, Process.SYSTEM_UID,
4296 mStartedUsers.keyAt(i));
4297 }
Amith Yamasani4860cfc2012-08-08 19:14:18 -07004298 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004299 }
4300 }
4301 }
4302
4303 final void ensureBootCompleted() {
4304 boolean booting;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004305 boolean enableScreen;
4306 synchronized (this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004307 booting = mBooting;
4308 mBooting = false;
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004309 enableScreen = !mBooted;
4310 mBooted = true;
4311 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004312
4313 if (booting) {
4314 finishBooting();
4315 }
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004316
4317 if (enableScreen) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07004318 enableScreenAfterBoot();
4319 }
4320 }
4321
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08004322 public final void activityPaused(IBinder token) {
4323 final long origId = Binder.clearCallingIdentity();
4324 mMainStack.activityPaused(token, false);
4325 Binder.restoreCallingIdentity(origId);
4326 }
4327
4328 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail,
4329 CharSequence description) {
4330 if (localLOGV) Slog.v(
4331 TAG, "Activity stopped: token=" + token);
4332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004333 // Refuse possible leaked file descriptors
4334 if (icicle != null && icicle.hasFileDescriptors()) {
4335 throw new IllegalArgumentException("File descriptors passed in Bundle");
4336 }
4337
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004338 ActivityRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339
4340 final long origId = Binder.clearCallingIdentity();
4341
4342 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004343 r = mMainStack.isInStackLocked(token);
4344 if (r != null) {
4345 r.stack.activityStoppedLocked(r, icicle, thumbnail, description);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004346 }
4347 }
4348
4349 if (r != null) {
4350 sendPendingThumbnail(r, null, null, null, false);
4351 }
4352
4353 trimApplications();
4354
4355 Binder.restoreCallingIdentity(origId);
4356 }
4357
4358 public final void activityDestroyed(IBinder token) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004359 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004360 mMainStack.activityDestroyed(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004361 }
4362
4363 public String getCallingPackage(IBinder token) {
4364 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004365 ActivityRecord r = getCallingRecordLocked(token);
Dianne Hackborn9bbcb912009-10-20 15:42:38 -07004366 return r != null && r.app != null ? r.info.packageName : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004367 }
4368 }
4369
4370 public ComponentName getCallingActivity(IBinder token) {
4371 synchronized (this) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004372 ActivityRecord r = getCallingRecordLocked(token);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004373 return r != null ? r.intent.getComponent() : null;
4374 }
4375 }
4376
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004377 private ActivityRecord getCallingRecordLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004378 ActivityRecord r = mMainStack.isInStackLocked(token);
4379 if (r == null) {
4380 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004381 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004382 return r.resultTo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 }
4384
4385 public ComponentName getActivityClassForToken(IBinder token) {
4386 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004387 ActivityRecord r = mMainStack.isInStackLocked(token);
4388 if (r == null) {
4389 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004390 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004391 return r.intent.getComponent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004392 }
4393 }
4394
4395 public String getPackageForToken(IBinder token) {
4396 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004397 ActivityRecord r = mMainStack.isInStackLocked(token);
4398 if (r == null) {
4399 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004401 return r.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 }
4403 }
4404
4405 public IIntentSender getIntentSender(int type,
4406 String packageName, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004407 int requestCode, Intent[] intents, String[] resolvedTypes,
4408 int flags, Bundle options) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004409 enforceNotIsolatedCaller("getIntentSender");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004410 // Refuse possible leaked file descriptors
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004411 if (intents != null) {
4412 if (intents.length < 1) {
4413 throw new IllegalArgumentException("Intents array length must be >= 1");
4414 }
4415 for (int i=0; i<intents.length; i++) {
4416 Intent intent = intents[i];
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004417 if (intent != null) {
4418 if (intent.hasFileDescriptors()) {
4419 throw new IllegalArgumentException("File descriptors passed in Intent");
4420 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07004421 if (type == ActivityManager.INTENT_SENDER_BROADCAST &&
Dianne Hackborn52b0ce02011-04-14 13:09:32 -07004422 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
4423 throw new IllegalArgumentException(
4424 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
4425 }
4426 intents[i] = new Intent(intent);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004427 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004428 }
4429 if (resolvedTypes != null && resolvedTypes.length != intents.length) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004430 throw new IllegalArgumentException(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004431 "Intent array length does not match resolvedTypes length");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004432 }
4433 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004434 if (options != null) {
4435 if (options.hasFileDescriptors()) {
4436 throw new IllegalArgumentException("File descriptors passed in options");
4437 }
4438 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07004439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004440 synchronized(this) {
4441 int callingUid = Binder.getCallingUid();
4442 try {
Jeff Brown10e89712011-07-08 18:52:57 -07004443 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004444 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004445 .getPackageUid(packageName, UserHandle.getUserId(callingUid));
4446 if (!UserHandle.isSameApp(callingUid, uid)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 String msg = "Permission Denial: getIntentSender() from pid="
4448 + Binder.getCallingPid()
4449 + ", uid=" + Binder.getCallingUid()
4450 + ", (need uid=" + uid + ")"
4451 + " is not allowed to send as package " + packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004452 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004453 throw new SecurityException(msg);
4454 }
4455 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004456
Amith Yamasani742a6712011-05-04 14:49:28 -07004457 if (DEBUG_MU)
4458 Slog.i(TAG_MU, "Getting intent sender for origCallingUid="
4459 + Binder.getOrigCallingUid());
4460 return getIntentSenderLocked(type, packageName, Binder.getOrigCallingUid(),
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004461 token, resultWho, requestCode, intents, resolvedTypes, flags, options);
Dianne Hackborn860755f2010-06-03 18:47:52 -07004462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463 } catch (RemoteException e) {
4464 throw new SecurityException(e);
4465 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004466 }
4467 }
4468
4469 IIntentSender getIntentSenderLocked(int type,
4470 String packageName, int callingUid, IBinder token, String resultWho,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07004471 int requestCode, Intent[] intents, String[] resolvedTypes, int flags,
4472 Bundle options) {
Amith Yamasani742a6712011-05-04 14:49:28 -07004473 if (DEBUG_MU)
4474 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004475 ActivityRecord activity = null;
Dianne Hackborna4972e92012-03-14 10:38:05 -07004476 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004477 activity = mMainStack.isInStackLocked(token);
4478 if (activity == null) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004479 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004481 if (activity.finishing) {
4482 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004483 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004484 }
4485
4486 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0;
4487 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0;
4488 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0;
4489 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT
4490 |PendingIntent.FLAG_UPDATE_CURRENT);
4491
4492 PendingIntentRecord.Key key = new PendingIntentRecord.Key(
4493 type, packageName, activity, resultWho,
Amith Yamasani4ea60692012-08-28 14:34:53 -07004494 requestCode, intents, resolvedTypes, flags, options,
4495 UserHandle.getUserId(callingUid));
Dianne Hackborn860755f2010-06-03 18:47:52 -07004496 WeakReference<PendingIntentRecord> ref;
4497 ref = mIntentSenderRecords.get(key);
4498 PendingIntentRecord rec = ref != null ? ref.get() : null;
4499 if (rec != null) {
4500 if (!cancelCurrent) {
4501 if (updateCurrent) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004502 if (rec.key.requestIntent != null) {
Adam Powell501d4a52012-04-30 15:03:57 -07004503 rec.key.requestIntent.replaceExtras(intents != null ?
4504 intents[intents.length - 1] : null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004505 }
4506 if (intents != null) {
4507 intents[intents.length-1] = rec.key.requestIntent;
4508 rec.key.allIntents = intents;
4509 rec.key.allResolvedTypes = resolvedTypes;
4510 } else {
4511 rec.key.allIntents = null;
4512 rec.key.allResolvedTypes = null;
4513 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004515 return rec;
4516 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004517 rec.canceled = true;
4518 mIntentSenderRecords.remove(key);
4519 }
4520 if (noCreate) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004521 return rec;
4522 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07004523 rec = new PendingIntentRecord(this, key, callingUid);
4524 mIntentSenderRecords.put(key, rec.ref);
Dianne Hackborna4972e92012-03-14 10:38:05 -07004525 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07004526 if (activity.pendingResults == null) {
4527 activity.pendingResults
4528 = new HashSet<WeakReference<PendingIntentRecord>>();
4529 }
4530 activity.pendingResults.add(rec.ref);
4531 }
4532 return rec;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004533 }
4534
4535 public void cancelIntentSender(IIntentSender sender) {
4536 if (!(sender instanceof PendingIntentRecord)) {
4537 return;
4538 }
4539 synchronized(this) {
4540 PendingIntentRecord rec = (PendingIntentRecord)sender;
4541 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004542 int uid = AppGlobals.getPackageManager()
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004543 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId());
4544 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 String msg = "Permission Denial: cancelIntentSender() from pid="
4546 + Binder.getCallingPid()
4547 + ", uid=" + Binder.getCallingUid()
4548 + " is not allowed to cancel packges "
4549 + rec.key.packageName;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004550 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551 throw new SecurityException(msg);
4552 }
4553 } catch (RemoteException e) {
4554 throw new SecurityException(e);
4555 }
4556 cancelIntentSenderLocked(rec, true);
4557 }
4558 }
4559
4560 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) {
4561 rec.canceled = true;
4562 mIntentSenderRecords.remove(rec.key);
4563 if (cleanActivity && rec.key.activity != null) {
4564 rec.key.activity.pendingResults.remove(rec.ref);
4565 }
4566 }
4567
4568 public String getPackageForIntentSender(IIntentSender pendingResult) {
4569 if (!(pendingResult instanceof PendingIntentRecord)) {
4570 return null;
4571 }
Brad Fitzpatrickb213d102010-04-19 11:58:52 -07004572 try {
4573 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4574 return res.key.packageName;
4575 } catch (ClassCastException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004576 }
4577 return null;
4578 }
4579
Christopher Tatec4a07d12012-04-06 14:19:13 -07004580 public int getUidForIntentSender(IIntentSender sender) {
4581 if (sender instanceof PendingIntentRecord) {
4582 try {
4583 PendingIntentRecord res = (PendingIntentRecord)sender;
4584 return res.uid;
4585 } catch (ClassCastException e) {
4586 }
4587 }
4588 return -1;
4589 }
4590
Dianne Hackborn6c418d52011-06-29 14:05:33 -07004591 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) {
4592 if (!(pendingResult instanceof PendingIntentRecord)) {
4593 return false;
4594 }
4595 try {
4596 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4597 if (res.key.allIntents == null) {
4598 return false;
4599 }
4600 for (int i=0; i<res.key.allIntents.length; i++) {
4601 Intent intent = res.key.allIntents[i];
4602 if (intent.getPackage() != null && intent.getComponent() != null) {
4603 return false;
4604 }
4605 }
4606 return true;
4607 } catch (ClassCastException e) {
4608 }
4609 return false;
4610 }
4611
Dianne Hackborn1927ae82012-06-22 15:21:36 -07004612 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) {
4613 if (!(pendingResult instanceof PendingIntentRecord)) {
4614 return false;
4615 }
4616 try {
4617 PendingIntentRecord res = (PendingIntentRecord)pendingResult;
4618 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) {
4619 return true;
4620 }
4621 return false;
4622 } catch (ClassCastException e) {
4623 }
4624 return false;
4625 }
4626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004627 public void setProcessLimit(int max) {
4628 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4629 "setProcessLimit()");
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004630 synchronized (this) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07004631 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004632 mProcessLimitOverride = max;
4633 }
4634 trimApplications();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004635 }
4636
4637 public int getProcessLimit() {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004638 synchronized (this) {
4639 return mProcessLimitOverride;
4640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004641 }
4642
4643 void foregroundTokenDied(ForegroundToken token) {
4644 synchronized (ActivityManagerService.this) {
4645 synchronized (mPidsSelfLocked) {
4646 ForegroundToken cur
4647 = mForegroundProcesses.get(token.pid);
4648 if (cur != token) {
4649 return;
4650 }
4651 mForegroundProcesses.remove(token.pid);
4652 ProcessRecord pr = mPidsSelfLocked.get(token.pid);
4653 if (pr == null) {
4654 return;
4655 }
4656 pr.forcingToForeground = null;
4657 pr.foregroundServices = false;
4658 }
4659 updateOomAdjLocked();
4660 }
4661 }
4662
4663 public void setProcessForeground(IBinder token, int pid, boolean isForeground) {
4664 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT,
4665 "setProcessForeground()");
4666 synchronized(this) {
4667 boolean changed = false;
4668
4669 synchronized (mPidsSelfLocked) {
4670 ProcessRecord pr = mPidsSelfLocked.get(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004671 if (pr == null && isForeground) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004672 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004673 return;
4674 }
4675 ForegroundToken oldToken = mForegroundProcesses.get(pid);
4676 if (oldToken != null) {
4677 oldToken.token.unlinkToDeath(oldToken, 0);
4678 mForegroundProcesses.remove(pid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08004679 if (pr != null) {
4680 pr.forcingToForeground = null;
4681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004682 changed = true;
4683 }
4684 if (isForeground && token != null) {
4685 ForegroundToken newToken = new ForegroundToken() {
4686 public void binderDied() {
4687 foregroundTokenDied(this);
4688 }
4689 };
4690 newToken.pid = pid;
4691 newToken.token = token;
4692 try {
4693 token.linkToDeath(newToken, 0);
4694 mForegroundProcesses.put(pid, newToken);
4695 pr.forcingToForeground = token;
4696 changed = true;
4697 } catch (RemoteException e) {
4698 // If the process died while doing this, we will later
4699 // do the cleanup with the process death link.
4700 }
4701 }
4702 }
4703
4704 if (changed) {
4705 updateOomAdjLocked();
4706 }
4707 }
4708 }
4709
4710 // =========================================================
4711 // PERMISSIONS
4712 // =========================================================
4713
4714 static class PermissionController extends IPermissionController.Stub {
4715 ActivityManagerService mActivityManagerService;
4716 PermissionController(ActivityManagerService activityManagerService) {
4717 mActivityManagerService = activityManagerService;
4718 }
4719
4720 public boolean checkPermission(String permission, int pid, int uid) {
4721 return mActivityManagerService.checkPermission(permission, pid,
4722 uid) == PackageManager.PERMISSION_GRANTED;
4723 }
4724 }
4725
4726 /**
4727 * This can be called with or without the global lock held.
4728 */
4729 int checkComponentPermission(String permission, int pid, int uid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08004730 int owningUid, boolean exported) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004731 // We might be performing an operation on behalf of an indirect binder
4732 // invocation, e.g. via {@link #openContentUri}. Check and adjust the
4733 // client identity accordingly before proceeding.
4734 Identity tlsIdentity = sCallerIdentity.get();
4735 if (tlsIdentity != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004736 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004737 + tlsIdentity.pid + "," + tlsIdentity.uid + "}");
4738 uid = tlsIdentity.uid;
4739 pid = tlsIdentity.pid;
4740 }
4741
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004742 if (pid == MY_PID) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004743 return PackageManager.PERMISSION_GRANTED;
4744 }
Dianne Hackborn5320eb82012-05-18 12:05:04 -07004745
4746 return ActivityManager.checkComponentPermission(permission, uid,
4747 owningUid, exported);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004748 }
4749
4750 /**
4751 * As the only public entry point for permissions checking, this method
4752 * can enforce the semantic that requesting a check on a null global
4753 * permission is automatically denied. (Internally a null permission
4754 * string is used when calling {@link #checkComponentPermission} in cases
4755 * when only uid-based security is needed.)
4756 *
4757 * This can be called with or without the global lock held.
4758 */
4759 public int checkPermission(String permission, int pid, int uid) {
4760 if (permission == null) {
4761 return PackageManager.PERMISSION_DENIED;
4762 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004763 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004764 }
4765
4766 /**
4767 * Binder IPC calls go through the public entry point.
4768 * This can be called with or without the global lock held.
4769 */
4770 int checkCallingPermission(String permission) {
4771 return checkPermission(permission,
4772 Binder.getCallingPid(),
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004773 UserHandle.getAppId(Binder.getCallingUid()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004774 }
4775
4776 /**
4777 * This can be called with or without the global lock held.
4778 */
4779 void enforceCallingPermission(String permission, String func) {
4780 if (checkCallingPermission(permission)
4781 == PackageManager.PERMISSION_GRANTED) {
4782 return;
4783 }
4784
4785 String msg = "Permission Denial: " + func + " from pid="
4786 + Binder.getCallingPid()
4787 + ", uid=" + Binder.getCallingUid()
4788 + " requires " + permission;
Joe Onorato8a9b2202010-02-26 18:56:32 -08004789 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004790 throw new SecurityException(msg);
4791 }
4792
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004793 /**
4794 * Determine if UID is holding permissions required to access {@link Uri} in
4795 * the given {@link ProviderInfo}. Final permission checking is always done
4796 * in {@link ContentProvider}.
4797 */
4798 private final boolean checkHoldingPermissionsLocked(
4799 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004800 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4801 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid);
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004802
4803 if (pi.applicationInfo.uid == uid) {
4804 return true;
4805 } else if (!pi.exported) {
4806 return false;
4807 }
4808
4809 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0;
4810 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004811 try {
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004812 // check if target holds top-level <provider> permissions
4813 if (!readMet && pi.readPermission != null
4814 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) {
4815 readMet = true;
4816 }
4817 if (!writeMet && pi.writePermission != null
4818 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) {
4819 writeMet = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004820 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004821
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004822 // track if unprotected read/write is allowed; any denied
4823 // <path-permission> below removes this ability
4824 boolean allowDefaultRead = pi.readPermission == null;
4825 boolean allowDefaultWrite = pi.writePermission == null;
Dianne Hackborn48058e82010-09-27 16:53:23 -07004826
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004827 // check if target holds any <path-permission> that match uri
4828 final PathPermission[] pps = pi.pathPermissions;
4829 if (pps != null) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004830 final String path = uri.getPath();
4831 int i = pps.length;
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004832 while (i > 0 && (!readMet || !writeMet)) {
Dianne Hackborn48058e82010-09-27 16:53:23 -07004833 i--;
4834 PathPermission pp = pps[i];
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004835 if (pp.match(path)) {
4836 if (!readMet) {
4837 final String pprperm = pp.getReadPermission();
4838 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for "
4839 + pprperm + " for " + pp.getPath()
4840 + ": match=" + pp.match(path)
4841 + " check=" + pm.checkUidPermission(pprperm, uid));
4842 if (pprperm != null) {
4843 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) {
4844 readMet = true;
4845 } else {
4846 allowDefaultRead = false;
4847 }
4848 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004849 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004850 if (!writeMet) {
4851 final String ppwperm = pp.getWritePermission();
4852 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm "
4853 + ppwperm + " for " + pp.getPath()
4854 + ": match=" + pp.match(path)
4855 + " check=" + pm.checkUidPermission(ppwperm, uid));
4856 if (ppwperm != null) {
4857 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) {
4858 writeMet = true;
4859 } else {
4860 allowDefaultWrite = false;
4861 }
4862 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004863 }
4864 }
4865 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07004866 }
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004867
4868 // grant unprotected <provider> read/write, if not blocked by
4869 // <path-permission> above
4870 if (allowDefaultRead) readMet = true;
4871 if (allowDefaultWrite) writeMet = true;
4872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004873 } catch (RemoteException e) {
4874 return false;
4875 }
Dianne Hackborn48058e82010-09-27 16:53:23 -07004876
Jeff Sharkey110a6b62012-03-12 11:12:41 -07004877 return readMet && writeMet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004878 }
4879
4880 private final boolean checkUriPermissionLocked(Uri uri, int uid,
4881 int modeFlags) {
4882 // Root gets to do everything.
Jeff Brown10e89712011-07-08 18:52:57 -07004883 if (uid == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004884 return true;
4885 }
4886 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid);
4887 if (perms == null) return false;
4888 UriPermission perm = perms.get(uri);
4889 if (perm == null) return false;
4890 return (modeFlags&perm.modeFlags) == modeFlags;
4891 }
4892
4893 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08004894 enforceNotIsolatedCaller("checkUriPermission");
4895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004896 // Another redirected-binder-call permissions check as in
4897 // {@link checkComponentPermission}.
4898 Identity tlsIdentity = sCallerIdentity.get();
4899 if (tlsIdentity != null) {
4900 uid = tlsIdentity.uid;
4901 pid = tlsIdentity.pid;
4902 }
4903
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004904 uid = UserHandle.getAppId(uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004905 // Our own process gets to do everything.
4906 if (pid == MY_PID) {
4907 return PackageManager.PERMISSION_GRANTED;
4908 }
4909 synchronized(this) {
4910 return checkUriPermissionLocked(uri, uid, modeFlags)
4911 ? PackageManager.PERMISSION_GRANTED
4912 : PackageManager.PERMISSION_DENIED;
4913 }
4914 }
4915
Dianne Hackborn39792d22010-08-19 18:01:52 -07004916 /**
4917 * Check if the targetPkg can be granted permission to access uri by
4918 * the callingUid using the given modeFlags. Throws a security exception
4919 * if callingUid is not allowed to do this. Returns the uid of the target
4920 * if the URI permission grant should be performed; returns -1 if it is not
4921 * needed (for example targetPkg already has permission to access the URI).
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004922 * If you already know the uid of the target, you can supply it in
4923 * lastTargetUid else set that to -1.
Dianne Hackborn39792d22010-08-19 18:01:52 -07004924 */
4925 int checkGrantUriPermissionLocked(int callingUid, String targetPkg,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004926 Uri uri, int modeFlags, int lastTargetUid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004927 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
4928 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
4929 if (modeFlags == 0) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004930 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004931 }
4932
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004933 if (targetPkg != null) {
4934 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4935 "Checking grant " + targetPkg + " permission to " + uri);
4936 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004937
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07004938 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004939
4940 // If this is not a content: uri, we can't do anything with it.
4941 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08004942 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08004943 "Can't grant URI permission for non-content URI: " + uri);
Dianne Hackborn39792d22010-08-19 18:01:52 -07004944 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004945 }
4946
4947 String name = uri.getAuthority();
4948 ProviderInfo pi = null;
Amith Yamasani742a6712011-05-04 14:49:28 -07004949 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004950 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004951 if (cpr != null) {
4952 pi = cpr.info;
4953 } else {
4954 try {
4955 pi = pm.resolveContentProvider(name,
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004956 PackageManager.GET_URI_PERMISSION_PATTERNS, UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004957 } catch (RemoteException ex) {
4958 }
4959 }
4960 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004961 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString());
Dianne Hackborn39792d22010-08-19 18:01:52 -07004962 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004963 }
4964
Dianne Hackborn21c241e2012-03-08 13:57:23 -08004965 int targetUid = lastTargetUid;
4966 if (targetUid < 0 && targetPkg != null) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004967 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07004968 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid));
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004969 if (targetUid < 0) {
4970 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4971 "Can't grant URI permission no uid for: " + targetPkg);
4972 return -1;
4973 }
4974 } catch (RemoteException ex) {
Dianne Hackborn39792d22010-08-19 18:01:52 -07004975 return -1;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004977 }
4978
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07004979 if (targetUid >= 0) {
4980 // First... does the target actually need this permission?
4981 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) {
4982 // No need to grant the target this permission.
4983 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
4984 "Target " + targetPkg + " already has full permission to " + uri);
4985 return -1;
4986 }
4987 } else {
4988 // First... there is no target package, so can anyone access it?
4989 boolean allowed = pi.exported;
4990 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
4991 if (pi.readPermission != null) {
4992 allowed = false;
4993 }
4994 }
4995 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
4996 if (pi.writePermission != null) {
4997 allowed = false;
4998 }
4999 }
5000 if (allowed) {
5001 return -1;
5002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005003 }
5004
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005005 // Second... is the provider allowing granting of URI permissions?
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005006 if (!pi.grantUriPermissions) {
5007 throw new SecurityException("Provider " + pi.packageName
5008 + "/" + pi.name
5009 + " does not allow granting of Uri permissions (uri "
5010 + uri + ")");
5011 }
5012 if (pi.uriPermissionPatterns != null) {
5013 final int N = pi.uriPermissionPatterns.length;
5014 boolean allowed = false;
5015 for (int i=0; i<N; i++) {
5016 if (pi.uriPermissionPatterns[i] != null
5017 && pi.uriPermissionPatterns[i].match(uri.getPath())) {
5018 allowed = true;
5019 break;
5020 }
5021 }
5022 if (!allowed) {
5023 throw new SecurityException("Provider " + pi.packageName
5024 + "/" + pi.name
5025 + " does not allow granting of permission to path of Uri "
5026 + uri);
5027 }
5028 }
5029
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005030 // Third... does the caller itself have permission to access
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005031 // this uri?
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005032 if (callingUid != Process.myUid()) {
5033 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
5034 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5035 throw new SecurityException("Uid " + callingUid
5036 + " does not have permission to uri " + uri);
5037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005038 }
5039 }
5040
Dianne Hackborn39792d22010-08-19 18:01:52 -07005041 return targetUid;
5042 }
5043
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005044 public int checkGrantUriPermission(int callingUid, String targetPkg,
5045 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005046 enforceNotIsolatedCaller("checkGrantUriPermission");
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005047 synchronized(this) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005048 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005049 }
5050 }
5051
Dianne Hackborn39792d22010-08-19 18:01:52 -07005052 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg,
5053 Uri uri, int modeFlags, UriPermissionOwner owner) {
5054 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5055 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5056 if (modeFlags == 0) {
5057 return;
5058 }
5059
5060 // So here we are: the caller has the assumed permission
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005061 // to the uri, and the target doesn't. Let's now give this to
5062 // the target.
5063
Joe Onorato8a9b2202010-02-26 18:56:32 -08005064 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn39792d22010-08-19 18:01:52 -07005065 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri);
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005067 HashMap<Uri, UriPermission> targetUris
5068 = mGrantedUriPermissions.get(targetUid);
5069 if (targetUris == null) {
5070 targetUris = new HashMap<Uri, UriPermission>();
5071 mGrantedUriPermissions.put(targetUid, targetUris);
5072 }
5073
5074 UriPermission perm = targetUris.get(uri);
5075 if (perm == null) {
5076 perm = new UriPermission(targetUid, uri);
5077 targetUris.put(uri, perm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005078 }
Dianne Hackbornb424b632010-08-18 15:59:05 -07005079
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005080 perm.modeFlags |= modeFlags;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005081 if (owner == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005082 perm.globalModeFlags |= modeFlags;
Vairavan Srinivasan91c12c22011-01-21 18:26:06 -08005083 } else {
5084 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) {
5085 perm.readOwners.add(owner);
5086 owner.addReadPermission(perm);
5087 }
5088 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) {
5089 perm.writeOwners.add(owner);
5090 owner.addWritePermission(perm);
5091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005092 }
5093 }
5094
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005095 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri,
5096 int modeFlags, UriPermissionOwner owner) {
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005097 if (targetPkg == null) {
5098 throw new NullPointerException("targetPkg");
5099 }
5100
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005101 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1);
Dianne Hackborn39792d22010-08-19 18:01:52 -07005102 if (targetUid < 0) {
5103 return;
5104 }
5105
5106 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner);
5107 }
5108
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005109 static class NeededUriGrants extends ArrayList<Uri> {
5110 final String targetPkg;
5111 final int targetUid;
5112 final int flags;
5113
5114 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) {
5115 targetPkg = _targetPkg;
5116 targetUid = _targetUid;
5117 flags = _flags;
5118 }
5119 }
5120
Dianne Hackborn39792d22010-08-19 18:01:52 -07005121 /**
5122 * Like checkGrantUriPermissionLocked, but takes an Intent.
5123 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005124 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid,
5125 String targetPkg, Intent intent, int mode, NeededUriGrants needed) {
Dianne Hackbornb424b632010-08-18 15:59:05 -07005126 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005127 "Checking URI perm to data=" + (intent != null ? intent.getData() : null)
5128 + " clip=" + (intent != null ? intent.getClipData() : null)
Dianne Hackbornb424b632010-08-18 15:59:05 -07005129 + " from " + intent + "; flags=0x"
5130 + Integer.toHexString(intent != null ? intent.getFlags() : 0));
5131
Dianne Hackborn90f4aaf2010-09-27 14:58:44 -07005132 if (targetPkg == null) {
5133 throw new NullPointerException("targetPkg");
5134 }
5135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005136 if (intent == null) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005137 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005138 }
5139 Uri data = intent.getData();
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005140 ClipData clip = intent.getClipData();
5141 if (data == null && clip == null) {
5142 return null;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005143 }
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005144 if (data != null) {
5145 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data,
5146 mode, needed != null ? needed.targetUid : -1);
5147 if (target > 0) {
5148 if (needed == null) {
5149 needed = new NeededUriGrants(targetPkg, target, mode);
5150 }
5151 needed.add(data);
5152 }
5153 }
5154 if (clip != null) {
5155 for (int i=0; i<clip.getItemCount(); i++) {
5156 Uri uri = clip.getItemAt(i).getUri();
5157 if (uri != null) {
5158 int target = -1;
5159 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri,
5160 mode, needed != null ? needed.targetUid : -1);
5161 if (target > 0) {
5162 if (needed == null) {
5163 needed = new NeededUriGrants(targetPkg, target, mode);
5164 }
5165 needed.add(uri);
5166 }
5167 } else {
5168 Intent clipIntent = clip.getItemAt(i).getIntent();
5169 if (clipIntent != null) {
5170 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked(
5171 callingUid, targetPkg, clipIntent, mode, needed);
5172 if (newNeeded != null) {
5173 needed = newNeeded;
5174 }
5175 }
5176 }
5177 }
5178 }
5179
5180 return needed;
Dianne Hackborn39792d22010-08-19 18:01:52 -07005181 }
5182
5183 /**
5184 * Like grantUriPermissionUncheckedLocked, but takes an Intent.
5185 */
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005186 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed,
5187 UriPermissionOwner owner) {
5188 if (needed != null) {
5189 for (int i=0; i<needed.size(); i++) {
5190 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg,
5191 needed.get(i), needed.flags, owner);
5192 }
5193 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005194 }
5195
5196 void grantUriPermissionFromIntentLocked(int callingUid,
5197 String targetPkg, Intent intent, UriPermissionOwner owner) {
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005198 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg,
Dianne Hackbornd9781fe2012-03-08 18:04:18 -08005199 intent, intent != null ? intent.getFlags() : 0, null);
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005200 if (needed == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005201 return;
5202 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07005203
Dianne Hackborn21c241e2012-03-08 13:57:23 -08005204 grantUriPermissionUncheckedFromIntentLocked(needed, owner);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005205 }
5206
5207 public void grantUriPermission(IApplicationThread caller, String targetPkg,
5208 Uri uri, int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005209 enforceNotIsolatedCaller("grantUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005210 synchronized(this) {
5211 final ProcessRecord r = getRecordForAppLocked(caller);
5212 if (r == null) {
5213 throw new SecurityException("Unable to find app for caller "
5214 + caller
5215 + " when granting permission to uri " + uri);
5216 }
5217 if (targetPkg == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005218 throw new IllegalArgumentException("null target");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219 }
5220 if (uri == null) {
Dianne Hackborn7e269642010-08-25 19:50:20 -07005221 throw new IllegalArgumentException("null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005222 }
5223
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005224 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005225 null);
5226 }
5227 }
5228
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005229 void removeUriPermissionIfNeededLocked(UriPermission perm) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005230 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION
5231 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) {
5232 HashMap<Uri, UriPermission> perms
5233 = mGrantedUriPermissions.get(perm.uid);
5234 if (perms != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005235 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005236 "Removing " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005237 perms.remove(perm.uri);
5238 if (perms.size() == 0) {
5239 mGrantedUriPermissions.remove(perm.uid);
5240 }
5241 }
5242 }
5243 }
5244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005245 private void revokeUriPermissionLocked(int callingUid, Uri uri,
5246 int modeFlags) {
5247 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5248 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5249 if (modeFlags == 0) {
5250 return;
5251 }
5252
Joe Onorato8a9b2202010-02-26 18:56:32 -08005253 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005254 "Revoking all granted permissions to " + uri);
5255
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005256 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005257
5258 final String authority = uri.getAuthority();
5259 ProviderInfo pi = null;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005260 int userId = UserHandle.getUserId(callingUid);
Amith Yamasani483f3b02012-03-13 16:08:00 -07005261 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005262 if (cpr != null) {
5263 pi = cpr.info;
5264 } else {
5265 try {
5266 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005267 PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005268 } catch (RemoteException ex) {
5269 }
5270 }
5271 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005272 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005273 return;
5274 }
5275
5276 // Does the caller have this permission on the URI?
Dianne Hackborn48058e82010-09-27 16:53:23 -07005277 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005278 // Right now, if you are not the original owner of the permission,
5279 // you are not allowed to revoke it.
5280 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) {
5281 throw new SecurityException("Uid " + callingUid
5282 + " does not have permission to uri " + uri);
5283 //}
5284 }
5285
5286 // Go through all of the permissions and remove any that match.
5287 final List<String> SEGMENTS = uri.getPathSegments();
5288 if (SEGMENTS != null) {
5289 final int NS = SEGMENTS.size();
5290 int N = mGrantedUriPermissions.size();
5291 for (int i=0; i<N; i++) {
5292 HashMap<Uri, UriPermission> perms
5293 = mGrantedUriPermissions.valueAt(i);
5294 Iterator<UriPermission> it = perms.values().iterator();
5295 toploop:
5296 while (it.hasNext()) {
5297 UriPermission perm = it.next();
5298 Uri targetUri = perm.uri;
5299 if (!authority.equals(targetUri.getAuthority())) {
5300 continue;
5301 }
5302 List<String> targetSegments = targetUri.getPathSegments();
5303 if (targetSegments == null) {
5304 continue;
5305 }
5306 if (targetSegments.size() < NS) {
5307 continue;
5308 }
5309 for (int j=0; j<NS; j++) {
5310 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) {
5311 continue toploop;
5312 }
5313 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08005314 if (DEBUG_URI_PERMISSION) Slog.v(TAG,
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08005315 "Revoking " + perm.uid + " permission to " + perm.uri);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005316 perm.clearModes(modeFlags);
5317 if (perm.modeFlags == 0) {
5318 it.remove();
5319 }
5320 }
5321 if (perms.size() == 0) {
5322 mGrantedUriPermissions.remove(
5323 mGrantedUriPermissions.keyAt(i));
5324 N--;
5325 i--;
5326 }
5327 }
5328 }
5329 }
5330
5331 public void revokeUriPermission(IApplicationThread caller, Uri uri,
5332 int modeFlags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005333 enforceNotIsolatedCaller("revokeUriPermission");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005334 synchronized(this) {
5335 final ProcessRecord r = getRecordForAppLocked(caller);
5336 if (r == null) {
5337 throw new SecurityException("Unable to find app for caller "
5338 + caller
5339 + " when revoking permission to uri " + uri);
5340 }
5341 if (uri == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005342 Slog.w(TAG, "revokeUriPermission: null uri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005343 return;
5344 }
5345
5346 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION
5347 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
5348 if (modeFlags == 0) {
5349 return;
5350 }
5351
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005352 final IPackageManager pm = AppGlobals.getPackageManager();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005353
5354 final String authority = uri.getAuthority();
5355 ProviderInfo pi = null;
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005356 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005357 if (cpr != null) {
5358 pi = cpr.info;
5359 } else {
5360 try {
5361 pi = pm.resolveContentProvider(authority,
Amith Yamasani483f3b02012-03-13 16:08:00 -07005362 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005363 } catch (RemoteException ex) {
5364 }
5365 }
5366 if (pi == null) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07005367 Slog.w(TAG, "No content provider found for permission revoke: "
5368 + uri.toSafeString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005369 return;
5370 }
5371
Dianne Hackborna0c283e2012-02-09 10:47:01 -08005372 revokeUriPermissionLocked(r.uid, uri, modeFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005373 }
5374 }
5375
Dianne Hackborn7e269642010-08-25 19:50:20 -07005376 @Override
5377 public IBinder newUriPermissionOwner(String name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005378 enforceNotIsolatedCaller("newUriPermissionOwner");
Dianne Hackborn7e269642010-08-25 19:50:20 -07005379 synchronized(this) {
5380 UriPermissionOwner owner = new UriPermissionOwner(this, name);
5381 return owner.getExternalTokenLocked();
5382 }
5383 }
5384
5385 @Override
5386 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg,
5387 Uri uri, int modeFlags) {
5388 synchronized(this) {
5389 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5390 if (owner == null) {
5391 throw new IllegalArgumentException("Unknown owner: " + token);
5392 }
5393 if (fromUid != Binder.getCallingUid()) {
5394 if (Binder.getCallingUid() != Process.myUid()) {
5395 // Only system code can grant URI permissions on behalf
5396 // of other users.
5397 throw new SecurityException("nice try");
5398 }
5399 }
5400 if (targetPkg == null) {
5401 throw new IllegalArgumentException("null target");
5402 }
5403 if (uri == null) {
5404 throw new IllegalArgumentException("null uri");
5405 }
5406
5407 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner);
5408 }
5409 }
5410
5411 @Override
5412 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) {
5413 synchronized(this) {
5414 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token);
5415 if (owner == null) {
5416 throw new IllegalArgumentException("Unknown owner: " + token);
5417 }
5418
5419 if (uri == null) {
5420 owner.removeUriPermissionsLocked(mode);
5421 } else {
5422 owner.removeUriPermissionLocked(uri, mode);
5423 }
5424 }
5425 }
5426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005427 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) {
5428 synchronized (this) {
5429 ProcessRecord app =
5430 who != null ? getRecordForAppLocked(who) : null;
5431 if (app == null) return;
5432
5433 Message msg = Message.obtain();
5434 msg.what = WAIT_FOR_DEBUGGER_MSG;
5435 msg.obj = app;
5436 msg.arg1 = waiting ? 1 : 0;
5437 mHandler.sendMessage(msg);
5438 }
5439 }
5440
5441 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07005442 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ);
5443 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005444 outInfo.availMem = Process.getFreeMemory();
Dianne Hackborn59325eb2012-05-09 18:45:20 -07005445 outInfo.totalMem = Process.getTotalMemory();
Dianne Hackborn7d608422011-08-07 16:24:18 -07005446 outInfo.threshold = homeAppMem;
5447 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2));
5448 outInfo.hiddenAppThreshold = hiddenAppMem;
5449 outInfo.secondaryServerThreshold = mProcessList.getMemLevel(
Dianne Hackborne02c88a2011-10-28 13:58:15 -07005450 ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07005451 outInfo.visibleAppThreshold = mProcessList.getMemLevel(
5452 ProcessList.VISIBLE_APP_ADJ);
5453 outInfo.foregroundAppThreshold = mProcessList.getMemLevel(
5454 ProcessList.FOREGROUND_APP_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005455 }
5456
5457 // =========================================================
5458 // TASK MANAGEMENT
5459 // =========================================================
5460
5461 public List getTasks(int maxNum, int flags,
5462 IThumbnailReceiver receiver) {
5463 ArrayList list = new ArrayList();
5464
5465 PendingThumbnailsRecord pending = null;
5466 IApplicationThread topThumbnail = null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005467 ActivityRecord topRecord = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468
5469 synchronized(this) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005470 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005471 TAG, "getTasks: max=" + maxNum + ", flags=" + flags
5472 + ", receiver=" + receiver);
5473
5474 if (checkCallingPermission(android.Manifest.permission.GET_TASKS)
5475 != PackageManager.PERMISSION_GRANTED) {
5476 if (receiver != null) {
5477 // If the caller wants to wait for pending thumbnails,
5478 // it ain't gonna get them.
5479 try {
5480 receiver.finished();
5481 } catch (RemoteException ex) {
5482 }
5483 }
5484 String msg = "Permission Denial: getTasks() from pid="
5485 + Binder.getCallingPid()
5486 + ", uid=" + Binder.getCallingUid()
5487 + " requires " + android.Manifest.permission.GET_TASKS;
Joe Onorato8a9b2202010-02-26 18:56:32 -08005488 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 throw new SecurityException(msg);
5490 }
5491
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005492 int pos = mMainStack.mHistory.size()-1;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005493 ActivityRecord next =
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005494 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005495 ActivityRecord top = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496 TaskRecord curTask = null;
5497 int numActivities = 0;
5498 int numRunning = 0;
5499 while (pos >= 0 && maxNum > 0) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005500 final ActivityRecord r = next;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501 pos--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005502 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005503
5504 // Initialize state for next task if needed.
5505 if (top == null ||
5506 (top.state == ActivityState.INITIALIZING
5507 && top.task == r.task)) {
5508 top = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005509 curTask = r.task;
5510 numActivities = numRunning = 0;
5511 }
5512
5513 // Add 'r' into the current task.
5514 numActivities++;
5515 if (r.app != null && r.app.thread != null) {
5516 numRunning++;
5517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518
Joe Onorato8a9b2202010-02-26 18:56:32 -08005519 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520 TAG, r.intent.getComponent().flattenToShortString()
5521 + ": task=" + r.task);
5522
5523 // If the next one is a different task, generate a new
5524 // TaskInfo entry for what we have.
5525 if (next == null || next.task != curTask) {
5526 ActivityManager.RunningTaskInfo ci
5527 = new ActivityManager.RunningTaskInfo();
5528 ci.id = curTask.taskId;
5529 ci.baseActivity = r.intent.getComponent();
5530 ci.topActivity = top.intent.getComponent();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07005531 if (top.thumbHolder != null) {
5532 ci.description = top.thumbHolder.lastDescription;
5533 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005534 ci.numActivities = numActivities;
5535 ci.numRunning = numRunning;
5536 //System.out.println(
5537 // "#" + maxNum + ": " + " descr=" + ci.description);
5538 if (ci.thumbnail == null && receiver != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005539 if (localLOGV) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 TAG, "State=" + top.state + "Idle=" + top.idle
5541 + " app=" + top.app
5542 + " thr=" + (top.app != null ? top.app.thread : null));
5543 if (top.state == ActivityState.RESUMED
5544 || top.state == ActivityState.PAUSING) {
5545 if (top.idle && top.app != null
5546 && top.app.thread != null) {
5547 topRecord = top;
5548 topThumbnail = top.app.thread;
5549 } else {
5550 top.thumbnailNeeded = true;
5551 }
5552 }
5553 if (pending == null) {
5554 pending = new PendingThumbnailsRecord(receiver);
5555 }
5556 pending.pendingRecords.add(top);
5557 }
5558 list.add(ci);
5559 maxNum--;
5560 top = null;
5561 }
5562 }
5563
5564 if (pending != null) {
5565 mPendingThumbnails.add(pending);
5566 }
5567 }
5568
Joe Onorato8a9b2202010-02-26 18:56:32 -08005569 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570
5571 if (topThumbnail != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005572 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08005574 topThumbnail.requestThumbnail(topRecord.appToken);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005576 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005577 sendPendingThumbnail(null, topRecord.appToken, null, null, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005578 }
5579 }
5580
5581 if (pending == null && receiver != null) {
5582 // In this case all thumbnails were available and the client
5583 // is being asked to be told when the remaining ones come in...
5584 // which is unusually, since the top-most currently running
5585 // activity should never have a canned thumbnail! Oh well.
5586 try {
5587 receiver.finished();
5588 } catch (RemoteException ex) {
5589 }
5590 }
5591
5592 return list;
5593 }
5594
5595 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum,
Amith Yamasani82644082012-08-03 13:09:11 -07005596 int flags, int userId) {
Amith Yamasani742a6712011-05-04 14:49:28 -07005597 final int callingUid = Binder.getCallingUid();
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005598 if (userId != UserHandle.getCallingUserId()) {
Amith Yamasani82644082012-08-03 13:09:11 -07005599 // Check if the caller is holding permissions for cross-user requests.
5600 if (checkComponentPermission(
5601 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
5602 Binder.getCallingPid(), callingUid, -1, true)
5603 != PackageManager.PERMISSION_GRANTED) {
5604 String msg = "Permission Denial: "
5605 + "Request to get recent tasks for user " + userId
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005606 + " but is calling from user " + UserHandle.getUserId(callingUid)
Amith Yamasani82644082012-08-03 13:09:11 -07005607 + "; this requires "
5608 + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
5609 Slog.w(TAG, msg);
5610 throw new SecurityException(msg);
5611 } else {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07005612 if (userId == UserHandle.USER_CURRENT) {
Amith Yamasani82644082012-08-03 13:09:11 -07005613 userId = mCurrentUserId;
5614 }
5615 }
5616 }
5617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618 synchronized (this) {
5619 enforceCallingPermission(android.Manifest.permission.GET_TASKS,
5620 "getRecentTasks()");
Dianne Hackborn8238e712012-04-24 11:15:40 -07005621 final boolean detailed = checkCallingPermission(
5622 android.Manifest.permission.GET_DETAILED_TASKS)
5623 == PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005625 IPackageManager pm = AppGlobals.getPackageManager();
Amith Yamasani82644082012-08-03 13:09:11 -07005626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 final int N = mRecentTasks.size();
5628 ArrayList<ActivityManager.RecentTaskInfo> res
5629 = new ArrayList<ActivityManager.RecentTaskInfo>(
5630 maxNum < N ? maxNum : N);
5631 for (int i=0; i<N && maxNum > 0; i++) {
5632 TaskRecord tr = mRecentTasks.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -07005633 // Only add calling user's recent tasks
Amith Yamasani82644082012-08-03 13:09:11 -07005634 if (tr.userId != userId) continue;
Dianne Hackborn905577f2011-09-07 18:31:28 -07005635 // Return the entry if desired by the caller. We always return
5636 // the first entry, because callers always expect this to be the
Amith Yamasani742a6712011-05-04 14:49:28 -07005637 // foreground app. We may filter others if the caller has
Dianne Hackborn905577f2011-09-07 18:31:28 -07005638 // not supplied RECENT_WITH_EXCLUDED and there is some reason
5639 // we should exclude the entry.
Amith Yamasani742a6712011-05-04 14:49:28 -07005640
Dianne Hackborn905577f2011-09-07 18:31:28 -07005641 if (i == 0
5642 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 || (tr.intent == null)
5644 || ((tr.intent.getFlags()
5645 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) {
5646 ActivityManager.RecentTaskInfo rti
5647 = new ActivityManager.RecentTaskInfo();
5648 rti.id = tr.numActivities > 0 ? tr.taskId : -1;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005649 rti.persistentId = tr.taskId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 rti.baseIntent = new Intent(
5651 tr.intent != null ? tr.intent : tr.affinityIntent);
Dianne Hackborn8238e712012-04-24 11:15:40 -07005652 if (!detailed) {
5653 rti.baseIntent.replaceExtras((Bundle)null);
5654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 rti.origActivity = tr.origActivity;
Dianne Hackbornd2835932010-12-13 16:28:46 -08005656 rti.description = tr.lastDescription;
5657
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005658 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) {
5659 // Check whether this activity is currently available.
5660 try {
5661 if (rti.origActivity != null) {
Amith Yamasani82644082012-08-03 13:09:11 -07005662 if (pm.getActivityInfo(rti.origActivity, 0, userId)
Amith Yamasani483f3b02012-03-13 16:08:00 -07005663 == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005664 continue;
5665 }
5666 } else if (rti.baseIntent != null) {
5667 if (pm.queryIntentActivities(rti.baseIntent,
Amith Yamasani82644082012-08-03 13:09:11 -07005668 null, 0, userId) == null) {
Dianne Hackborn53d9264d2010-04-13 12:49:14 -07005669 continue;
5670 }
5671 }
5672 } catch (RemoteException e) {
5673 // Will never happen.
5674 }
5675 }
5676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005677 res.add(rti);
5678 maxNum--;
5679 }
5680 }
5681 return res;
5682 }
5683 }
5684
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005685 private TaskRecord taskForIdLocked(int id) {
5686 final int N = mRecentTasks.size();
5687 for (int i=0; i<N; i++) {
5688 TaskRecord tr = mRecentTasks.get(i);
5689 if (tr.taskId == id) {
5690 return tr;
Dianne Hackbornd94df452011-02-16 18:53:31 -08005691 }
5692 }
5693 return null;
5694 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005695
5696 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) {
5697 synchronized (this) {
5698 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER,
5699 "getTaskThumbnails()");
5700 TaskRecord tr = taskForIdLocked(id);
5701 if (tr != null) {
5702 return mMainStack.getTaskThumbnailsLocked(tr);
5703 }
5704 }
5705 return null;
5706 }
5707
5708 public boolean removeSubTask(int taskId, int subTaskIndex) {
5709 synchronized (this) {
5710 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5711 "removeSubTask()");
5712 long ident = Binder.clearCallingIdentity();
5713 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005714 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex,
5715 true) != null;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005716 } finally {
5717 Binder.restoreCallingIdentity(ident);
5718 }
5719 }
5720 }
5721
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005722 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) {
5723 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005724 Intent baseIntent = new Intent(
5725 tr.intent != null ? tr.intent : tr.affinityIntent);
5726 ComponentName component = baseIntent.getComponent();
5727 if (component == null) {
5728 Slog.w(TAG, "Now component for base intent of task: " + tr);
5729 return;
5730 }
5731
5732 // Find any running services associated with this app.
Dianne Hackborn599db5c2012-08-03 19:28:48 -07005733 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005734
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005735 if (killProcesses) {
5736 // Find any running processes associated with this app.
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005737 final String pkg = component.getPackageName();
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005738 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>();
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005739 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap();
5740 for (SparseArray<ProcessRecord> uids : pmap.values()) {
5741 for (int i=0; i<uids.size(); i++) {
5742 ProcessRecord proc = uids.valueAt(i);
5743 if (proc.userId != tr.userId) {
5744 continue;
5745 }
5746 if (!proc.pkgList.contains(pkg)) {
5747 continue;
5748 }
5749 procs.add(proc);
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005750 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005751 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005752
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005753 // Kill the running processes.
5754 for (int i=0; i<procs.size(); i++) {
5755 ProcessRecord pr = procs.get(i);
5756 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
5757 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task");
5758 EventLog.writeEvent(EventLogTags.AM_KILL, pr.pid,
5759 pr.processName, pr.setAdj, "remove task");
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07005760 pr.killedBackground = true;
Dianne Hackborn8894cc52011-07-01 16:28:17 -07005761 Process.killProcessQuiet(pr.pid);
5762 } else {
5763 pr.waitingToKill = "remove task";
5764 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005765 }
5766 }
5767 }
5768
5769 public boolean removeTask(int taskId, int flags) {
5770 synchronized (this) {
5771 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS,
5772 "removeTask()");
5773 long ident = Binder.clearCallingIdentity();
5774 try {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005775 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1,
5776 false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005777 if (r != null) {
5778 mRecentTasks.remove(r.task);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005779 cleanUpRemovedTaskLocked(r.task, flags);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005780 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005781 } else {
5782 TaskRecord tr = null;
5783 int i=0;
5784 while (i < mRecentTasks.size()) {
5785 TaskRecord t = mRecentTasks.get(i);
5786 if (t.taskId == taskId) {
5787 tr = t;
5788 break;
5789 }
5790 i++;
5791 }
5792 if (tr != null) {
5793 if (tr.numActivities <= 0) {
5794 // Caller is just removing a recent task that is
5795 // not actively running. That is easy!
5796 mRecentTasks.remove(i);
Dianne Hackborn9da2d402012-03-15 13:43:08 -07005797 cleanUpRemovedTaskLocked(tr, flags);
5798 return true;
Dianne Hackborneeb1dca2011-09-08 13:30:11 -07005799 } else {
5800 Slog.w(TAG, "removeTask: task " + taskId
5801 + " does not have activities to remove, "
5802 + " but numActivities=" + tr.numActivities
5803 + ": " + tr);
5804 }
5805 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005806 }
5807 } finally {
5808 Binder.restoreCallingIdentity(ident);
5809 }
5810 }
5811 return false;
5812 }
Dianne Hackbornd94df452011-02-16 18:53:31 -08005813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005814 private final int findAffinityTaskTopLocked(int startIndex, String affinity) {
5815 int j;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005816 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 TaskRecord jt = startTask;
5818
5819 // First look backwards
5820 for (j=startIndex-1; j>=0; 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 jt = r.task;
5824 if (affinity.equals(jt.affinity)) {
5825 return j;
5826 }
5827 }
5828 }
5829
5830 // Now look forwards
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005831 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 jt = startTask;
5833 for (j=startIndex+1; j<N; j++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005834 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 if (r.task != jt) {
5836 if (affinity.equals(jt.affinity)) {
5837 return j;
5838 }
5839 jt = r.task;
5840 }
5841 }
5842
5843 // Might it be at the top?
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005844 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 return N-1;
5846 }
5847
5848 return -1;
5849 }
5850
5851 /**
Dianne Hackbornb06ea702009-07-13 13:07:51 -07005852 * TODO: Add mController hook
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 */
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005854 public void moveTaskToFront(int task, int flags, Bundle options) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5856 "moveTaskToFront()");
5857
5858 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005859 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5860 Binder.getCallingUid(), "Task to front")) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005861 ActivityOptions.abort(options);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005862 return;
5863 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 final long origId = Binder.clearCallingIdentity();
5865 try {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005866 TaskRecord tr = taskForIdLocked(task);
5867 if (tr != null) {
5868 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5869 mMainStack.mUserLeaving = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005870 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005871 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5872 // Caller wants the home activity moved with it. To accomplish this,
5873 // we'll just move the home task to the top first.
5874 mMainStack.moveHomeToFrontLocked();
5875 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005876 mMainStack.moveTaskToFrontLocked(tr, null, options);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07005877 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005878 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005879 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
5880 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005881 if (hr.task.taskId == task) {
Dianne Hackbornd94df452011-02-16 18:53:31 -08005882 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
5883 mMainStack.mUserLeaving = true;
5884 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08005885 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
5886 // Caller wants the home activity moved with it. To accomplish this,
5887 // we'll just move the home task to the top first.
5888 mMainStack.moveHomeToFrontLocked();
5889 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005890 mMainStack.moveTaskToFrontLocked(hr.task, null, options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005891 return;
5892 }
5893 }
5894 } finally {
5895 Binder.restoreCallingIdentity(origId);
5896 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07005897 ActivityOptions.abort(options);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005898 }
5899 }
5900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005901 public void moveTaskToBack(int task) {
5902 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5903 "moveTaskToBack()");
5904
5905 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005906 if (mMainStack.mResumedActivity != null
5907 && mMainStack.mResumedActivity.task.taskId == task) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005908 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5909 Binder.getCallingUid(), "Task to back")) {
5910 return;
5911 }
5912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005913 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005914 mMainStack.moveTaskToBackLocked(task, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005915 Binder.restoreCallingIdentity(origId);
5916 }
5917 }
5918
5919 /**
5920 * Moves an activity, and all of the other activities within the same task, to the bottom
5921 * of the history stack. The activity's order within the task is unchanged.
5922 *
5923 * @param token A reference to the activity we wish to move
5924 * @param nonRoot If false then this only works if the activity is the root
5925 * of a task; if true it will work for any activity in a task.
5926 * @return Returns true if the move completed, false if not.
5927 */
5928 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08005929 enforceNotIsolatedCaller("moveActivityTaskToBack");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005930 synchronized(this) {
5931 final long origId = Binder.clearCallingIdentity();
5932 int taskId = getTaskForActivityLocked(token, !nonRoot);
5933 if (taskId >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005934 return mMainStack.moveTaskToBackLocked(taskId, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005935 }
5936 Binder.restoreCallingIdentity(origId);
5937 }
5938 return false;
5939 }
5940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005941 public void moveTaskBackwards(int task) {
5942 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS,
5943 "moveTaskBackwards()");
5944
5945 synchronized(this) {
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07005946 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(),
5947 Binder.getCallingUid(), "Task backwards")) {
5948 return;
5949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005950 final long origId = Binder.clearCallingIdentity();
5951 moveTaskBackwardsLocked(task);
5952 Binder.restoreCallingIdentity(origId);
5953 }
5954 }
5955
5956 private final void moveTaskBackwardsLocked(int task) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08005957 Slog.e(TAG, "moveTaskBackwards not yet implemented!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005958 }
5959
5960 public int getTaskForActivity(IBinder token, boolean onlyRoot) {
5961 synchronized(this) {
5962 return getTaskForActivityLocked(token, onlyRoot);
5963 }
5964 }
5965
5966 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005967 final int N = mMainStack.mHistory.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005968 TaskRecord lastTask = null;
5969 for (int i=0; i<N; i++) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005970 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005971 if (r.appToken == token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 if (!onlyRoot || lastTask != r.task) {
5973 return r.task.taskId;
5974 }
5975 return -1;
5976 }
5977 lastTask = r.task;
5978 }
5979
5980 return -1;
5981 }
5982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 // =========================================================
5984 // THUMBNAILS
5985 // =========================================================
5986
5987 public void reportThumbnail(IBinder token,
5988 Bitmap thumbnail, CharSequence description) {
5989 //System.out.println("Report thumbnail for " + token + ": " + thumbnail);
5990 final long origId = Binder.clearCallingIdentity();
5991 sendPendingThumbnail(null, token, thumbnail, description, true);
5992 Binder.restoreCallingIdentity(origId);
5993 }
5994
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07005995 final void sendPendingThumbnail(ActivityRecord r, IBinder token,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 Bitmap thumbnail, CharSequence description, boolean always) {
5997 TaskRecord task = null;
5998 ArrayList receivers = null;
5999
6000 //System.out.println("Send pending thumbnail: " + r);
6001
6002 synchronized(this) {
6003 if (r == null) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07006004 r = mMainStack.isInStackLocked(token);
6005 if (r == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006006 return;
6007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07006009 if (thumbnail == null && r.thumbHolder != null) {
6010 thumbnail = r.thumbHolder.lastThumbnail;
6011 description = r.thumbHolder.lastDescription;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 }
6013 if (thumbnail == null && !always) {
6014 // If there is no thumbnail, and this entry is not actually
6015 // going away, then abort for now and pick up the next
6016 // thumbnail we get.
6017 return;
6018 }
6019 task = r.task;
6020
6021 int N = mPendingThumbnails.size();
6022 int i=0;
6023 while (i<N) {
6024 PendingThumbnailsRecord pr =
6025 (PendingThumbnailsRecord)mPendingThumbnails.get(i);
6026 //System.out.println("Looking in " + pr.pendingRecords);
6027 if (pr.pendingRecords.remove(r)) {
6028 if (receivers == null) {
6029 receivers = new ArrayList();
6030 }
6031 receivers.add(pr);
6032 if (pr.pendingRecords.size() == 0) {
6033 pr.finished = true;
6034 mPendingThumbnails.remove(i);
6035 N--;
6036 continue;
6037 }
6038 }
6039 i++;
6040 }
6041 }
6042
6043 if (receivers != null) {
6044 final int N = receivers.size();
6045 for (int i=0; i<N; i++) {
6046 try {
6047 PendingThumbnailsRecord pr =
6048 (PendingThumbnailsRecord)receivers.get(i);
6049 pr.receiver.newThumbnail(
6050 task != null ? task.taskId : -1, thumbnail, description);
6051 if (pr.finished) {
6052 pr.receiver.finished();
6053 }
6054 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006055 Slog.w(TAG, "Exception thrown when sending thumbnail", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 }
6057 }
6058 }
6059 }
6060
6061 // =========================================================
6062 // CONTENT PROVIDERS
6063 // =========================================================
6064
Jeff Brown10e89712011-07-08 18:52:57 -07006065 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) {
6066 List<ProviderInfo> providers = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006067 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006068 providers = AppGlobals.getPackageManager().
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006069 queryContentProviders(app.processName, app.uid,
Dianne Hackborn1655be42009-05-08 14:29:01 -07006070 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 } catch (RemoteException ex) {
6072 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006073 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006074 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid);
6075 int userId = app.userId;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 if (providers != null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006077 int N = providers.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 for (int i=0; i<N; i++) {
6079 ProviderInfo cpi =
6080 (ProviderInfo)providers.get(i);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006081 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6082 cpi.name, cpi.flags);
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006083 if (singleton && UserHandle.getUserId(app.uid) != 0) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006084 // This is a singleton provider, but a user besides the
6085 // default user is asking to initialize a process it runs
6086 // in... well, no, it doesn't actually run in this process,
6087 // it runs in the process of the default user. Get rid of it.
6088 providers.remove(i);
6089 N--;
6090 continue;
6091 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006092
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006093 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006094 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006095 if (cpr == null) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006096 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton);
Amith Yamasani742a6712011-05-04 14:49:28 -07006097 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006098 }
Amith Yamasani742a6712011-05-04 14:49:28 -07006099 if (DEBUG_MU)
6100 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006101 app.pubProviders.put(cpi.name, cpr);
6102 app.addPackage(cpi.applicationInfo.packageName);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07006103 ensurePackageDexOpt(cpi.applicationInfo.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 }
6105 }
6106 return providers;
6107 }
6108
Jeff Sharkey110a6b62012-03-12 11:12:41 -07006109 /**
6110 * Check if {@link ProcessRecord} has a possible chance at accessing the
6111 * given {@link ProviderInfo}. Final permission checking is always done
6112 * in {@link ContentProvider}.
6113 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 private final String checkContentProviderPermissionLocked(
Dianne Hackbornb424b632010-08-18 15:59:05 -07006115 ProviderInfo cpi, ProcessRecord r) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006117 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006118 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006119 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006120 == PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 return null;
6122 }
6123 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006124 cpi.applicationInfo.uid, cpi.exported)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006125 == PackageManager.PERMISSION_GRANTED) {
6126 return null;
6127 }
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006128
6129 PathPermission[] pps = cpi.pathPermissions;
6130 if (pps != null) {
6131 int i = pps.length;
6132 while (i > 0) {
6133 i--;
6134 PathPermission pp = pps[i];
6135 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006136 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackbornb424b632010-08-18 15:59:05 -07006137 == PackageManager.PERMISSION_GRANTED) {
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006138 return null;
6139 }
6140 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006141 cpi.applicationInfo.uid, cpi.exported)
Dianne Hackborn2af632f2009-07-08 14:56:37 -07006142 == PackageManager.PERMISSION_GRANTED) {
6143 return null;
6144 }
6145 }
6146 }
6147
Dianne Hackbornb424b632010-08-18 15:59:05 -07006148 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid);
6149 if (perms != null) {
6150 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) {
6151 if (uri.getKey().getAuthority().equals(cpi.authority)) {
6152 return null;
6153 }
6154 }
6155 }
6156
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08006157 String msg;
6158 if (!cpi.exported) {
6159 msg = "Permission Denial: opening provider " + cpi.name
6160 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6161 + ", uid=" + callingUid + ") that is not exported from uid "
6162 + cpi.applicationInfo.uid;
6163 } else {
6164 msg = "Permission Denial: opening provider " + cpi.name
6165 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid
6166 + ", uid=" + callingUid + ") requires "
6167 + cpi.readPermission + " or " + cpi.writePermission;
6168 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08006169 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006170 return msg;
6171 }
6172
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006173 ContentProviderConnection incProviderCountLocked(ProcessRecord r,
6174 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006175 if (r != null) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006176 for (int i=0; i<r.conProviders.size(); i++) {
6177 ContentProviderConnection conn = r.conProviders.get(i);
6178 if (conn.provider == cpr) {
6179 if (DEBUG_PROVIDER) Slog.v(TAG,
6180 "Adding provider requested by "
6181 + r.processName + " from process "
6182 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
6183 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6184 if (stable) {
6185 conn.stableCount++;
6186 conn.numStableIncs++;
6187 } else {
6188 conn.unstableCount++;
6189 conn.numUnstableIncs++;
6190 }
6191 return conn;
6192 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006193 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006194 ContentProviderConnection conn = new ContentProviderConnection(cpr, r);
6195 if (stable) {
6196 conn.stableCount = 1;
6197 conn.numStableIncs = 1;
6198 } else {
6199 conn.unstableCount = 1;
6200 conn.numUnstableIncs = 1;
6201 }
6202 cpr.connections.add(conn);
6203 r.conProviders.add(conn);
6204 return conn;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006205 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006206 cpr.addExternalProcessHandleLocked(externalProcessToken);
6207 return null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006208 }
6209
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006210 boolean decProviderCountLocked(ContentProviderConnection conn,
6211 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) {
6212 if (conn != null) {
6213 cpr = conn.provider;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006214 if (DEBUG_PROVIDER) Slog.v(TAG,
6215 "Removing provider requested by "
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006216 + conn.client.processName + " from process "
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006217 + cpr.info.processName + ": " + cpr.name.flattenToShortString()
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006218 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount);
6219 if (stable) {
6220 conn.stableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006221 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006222 conn.unstableCount--;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006223 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006224 if (conn.stableCount == 0 && conn.unstableCount == 0) {
6225 cpr.connections.remove(conn);
6226 conn.client.conProviders.remove(conn);
6227 return true;
6228 }
6229 return false;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006230 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006231 cpr.removeExternalProcessHandleLocked(externalProcessToken);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006232 return false;
6233 }
6234
Amith Yamasani742a6712011-05-04 14:49:28 -07006235 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller,
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006236 String name, IBinder token, boolean stable) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 ContentProviderRecord cpr;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006238 ContentProviderConnection conn = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 ProviderInfo cpi = null;
6240
6241 synchronized(this) {
6242 ProcessRecord r = null;
6243 if (caller != null) {
6244 r = getRecordForAppLocked(caller);
6245 if (r == null) {
6246 throw new SecurityException(
6247 "Unable to find app for caller " + caller
6248 + " (pid=" + Binder.getCallingPid()
6249 + ") when getting content provider " + name);
6250 }
6251 }
6252
6253 // First check if this content provider has been published...
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006254 int userId = UserHandle.getUserId(r != null ? r.uid : Binder.getCallingUid());
Amith Yamasani742a6712011-05-04 14:49:28 -07006255 cpr = mProviderMap.getProviderByName(name, userId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006256 boolean providerRunning = cpr != null;
6257 if (providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 cpi = cpr.info;
Dianne Hackbornb424b632010-08-18 15:59:05 -07006259 String msg;
6260 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6261 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 }
6263
6264 if (r != null && cpr.canRunHere(r)) {
6265 // This provider has been published or is in the process
6266 // of being published... but it is also allowed to run
6267 // in the caller's process, so don't make a connection
6268 // and just let the caller instantiate its own instance.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006269 ContentProviderHolder holder = cpr.newHolder(null);
6270 // don't give caller the provider object, it needs
6271 // to make its own.
6272 holder.provider = null;
6273 return holder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 }
6275
6276 final long origId = Binder.clearCallingIdentity();
6277
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006278 // In this case the provider instance already exists, so we can
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 // return it right away.
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006280 conn = incProviderCountLocked(r, cpr, token, stable);
6281 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) {
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006282 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn32907cf2010-06-10 17:50:20 -07006283 // If this is a perceptible app accessing the provider,
Dianne Hackborn906497c2010-05-10 15:57:38 -07006284 // make sure to count it as being accessed and thus
6285 // back up on the LRU list. This is good because
6286 // content providers are often expensive to start.
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006287 updateLruProcessLocked(cpr.proc, false, true);
Dianne Hackborn906497c2010-05-10 15:57:38 -07006288 }
Dianne Hackborn6f86c0e2010-05-11 14:20:52 -07006289 }
6290
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006291 if (cpr.proc != null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006292 if (false) {
6293 if (cpr.name.flattenToShortString().equals(
6294 "com.android.providers.calendar/.CalendarProvider2")) {
6295 Slog.v(TAG, "****************** KILLING "
6296 + cpr.name.flattenToShortString());
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006297 Process.killProcess(cpr.proc.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006298 }
6299 }
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006300 boolean success = updateOomAdjLocked(cpr.proc);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006301 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success);
6302 // NOTE: there is still a race here where a signal could be
6303 // pending on the process even though we managed to update its
6304 // adj level. Not sure what to do about this, but at least
6305 // the race is now smaller.
6306 if (!success) {
6307 // Uh oh... it looks like the provider's process
6308 // has been killed on us. We need to wait for a new
6309 // process to be started, and make sure its death
6310 // doesn't kill our process.
6311 Slog.i(TAG,
6312 "Existing provider " + cpr.name.flattenToShortString()
6313 + " is crashing; detaching " + r);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006314 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable);
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006315 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006316 if (!lastRef) {
6317 // This wasn't the last ref our process had on
6318 // the provider... we have now been killed, bail.
6319 return null;
6320 }
6321 providerRunning = false;
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006322 conn = null;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 }
6325
6326 Binder.restoreCallingIdentity(origId);
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006329 boolean singleton;
Dianne Hackborn295e3c22011-08-25 13:19:08 -07006330 if (!providerRunning) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006332 cpi = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07006333 resolveContentProvider(name,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006334 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 } catch (RemoteException ex) {
6336 }
6337 if (cpi == null) {
6338 return null;
6339 }
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006340 singleton = isSingleton(cpi.processName, cpi.applicationInfo,
6341 cpi.name, cpi.flags);
6342 if (singleton) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07006343 userId = 0;
6344 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006345 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07006346
Dianne Hackbornb424b632010-08-18 15:59:05 -07006347 String msg;
6348 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) {
6349 throw new SecurityException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006350 }
6351
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07006352 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006353 && !cpi.processName.equals("system")) {
6354 // If this content provider does not run in the system
6355 // process, and the system is not yet ready to run other
6356 // processes, then fail fast instead of hanging.
6357 throw new IllegalArgumentException(
6358 "Attempt to launch content provider before system ready");
6359 }
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006360
Dianne Hackborn80a4af22012-08-27 19:18:31 -07006361 // Make sure that the user who owns this provider is started. If not,
6362 // we don't want to allow it to run.
6363 if (mStartedUsers.get(userId) == null) {
6364 Slog.w(TAG, "Unable to launch app "
6365 + cpi.applicationInfo.packageName + "/"
6366 + cpi.applicationInfo.uid + " for provider "
6367 + name + ": user " + userId + " is stopped");
6368 return null;
6369 }
6370
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006371 ComponentName comp = new ComponentName(cpi.packageName, cpi.name);
Amith Yamasani483f3b02012-03-13 16:08:00 -07006372 cpr = mProviderMap.getProviderByClass(comp, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006373 final boolean firstClass = cpr == null;
6374 if (firstClass) {
6375 try {
6376 ApplicationInfo ai =
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07006377 AppGlobals.getPackageManager().
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 getApplicationInfo(
6379 cpi.applicationInfo.packageName,
Amith Yamasani483f3b02012-03-13 16:08:00 -07006380 STOCK_PM_FLAGS, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 if (ai == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006382 Slog.w(TAG, "No package info for content provider "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 + cpi.name);
6384 return null;
6385 }
Amith Yamasani483f3b02012-03-13 16:08:00 -07006386 ai = getAppInfoForUser(ai, userId);
Dianne Hackborn7d19e022012-08-07 19:12:33 -07006387 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006388 } catch (RemoteException ex) {
6389 // pm is in same process, this will never happen.
6390 }
6391 }
6392
6393 if (r != null && cpr.canRunHere(r)) {
6394 // If this is a multiprocess provider, then just return its
6395 // info and allow the caller to instantiate it. Only do
6396 // this if the provider is the same user as the caller's
6397 // process, or can run as root (so can be in any process).
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006398 return cpr.newHolder(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006399 }
6400
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006401 if (DEBUG_PROVIDER) {
6402 RuntimeException e = new RuntimeException("here");
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006403 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid
Dianne Hackborna1e989b2009-09-01 19:54:29 -07006404 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 }
6406
6407 // This is single process, and our app is now connecting to it.
6408 // See if we are already in the process of launching this
6409 // provider.
6410 final int N = mLaunchingProviders.size();
6411 int i;
6412 for (i=0; i<N; i++) {
6413 if (mLaunchingProviders.get(i) == cpr) {
6414 break;
6415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 }
6417
6418 // If the provider is not already being launched, then get it
6419 // started.
6420 if (i >= N) {
6421 final long origId = Binder.clearCallingIdentity();
Dianne Hackborne7f97212011-02-24 14:40:20 -08006422
6423 try {
6424 // Content provider is now in use, its package can't be stopped.
6425 try {
6426 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07006427 cpr.appInfo.packageName, false, userId);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006428 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006429 } catch (IllegalArgumentException e) {
6430 Slog.w(TAG, "Failed trying to unstop package "
6431 + cpr.appInfo.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006432 }
6433
6434 ProcessRecord proc = startProcessLocked(cpi.processName,
6435 cpr.appInfo, false, 0, "content provider",
6436 new ComponentName(cpi.applicationInfo.packageName,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006437 cpi.name), false, false);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006438 if (proc == null) {
6439 Slog.w(TAG, "Unable to launch app "
6440 + cpi.applicationInfo.packageName + "/"
6441 + cpi.applicationInfo.uid + " for provider "
6442 + name + ": process is bad");
6443 return null;
6444 }
6445 cpr.launchingApp = proc;
6446 mLaunchingProviders.add(cpr);
6447 } finally {
6448 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006450 }
6451
6452 // Make sure the provider is published (the same provider class
6453 // may be published under multiple names).
6454 if (firstClass) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006455 mProviderMap.putProviderByClass(comp, cpr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 }
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006457
Amith Yamasani742a6712011-05-04 14:49:28 -07006458 mProviderMap.putProviderByName(name, cpr);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006459 conn = incProviderCountLocked(r, cpr, token, stable);
6460 if (conn != null) {
6461 conn.waiting = true;
6462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006463 }
6464 }
6465
6466 // Wait for the provider to be published...
6467 synchronized (cpr) {
6468 while (cpr.provider == null) {
6469 if (cpr.launchingApp == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006470 Slog.w(TAG, "Unable to launch app "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 + cpi.applicationInfo.packageName + "/"
6472 + cpi.applicationInfo.uid + " for provider "
6473 + name + ": launching app became null");
Doug Zongker2bec3d42009-12-04 12:52:44 -08006474 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 cpi.applicationInfo.packageName,
6476 cpi.applicationInfo.uid, name);
6477 return null;
6478 }
6479 try {
Amith Yamasani742a6712011-05-04 14:49:28 -07006480 if (DEBUG_MU) {
6481 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp="
6482 + cpr.launchingApp);
6483 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006484 if (conn != null) {
6485 conn.waiting = true;
6486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 cpr.wait();
6488 } catch (InterruptedException ex) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006489 } finally {
6490 if (conn != null) {
6491 conn.waiting = false;
6492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 }
6494 }
6495 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006496 return cpr != null ? cpr.newHolder(conn) : null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 }
6498
6499 public final ContentProviderHolder getContentProvider(
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006500 IApplicationThread caller, String name, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006501 enforceNotIsolatedCaller("getContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 if (caller == null) {
6503 String msg = "null IApplicationThread when getting content provider "
6504 + name;
Joe Onorato8a9b2202010-02-26 18:56:32 -08006505 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 throw new SecurityException(msg);
6507 }
6508
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006509 return getContentProviderImpl(caller, name, null, stable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006510 }
6511
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006512 public ContentProviderHolder getContentProviderExternal(String name, IBinder token) {
6513 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6514 "Do not have permission in call getContentProviderExternal()");
6515 return getContentProviderExternalUnchecked(name, token);
6516 }
6517
6518 private ContentProviderHolder getContentProviderExternalUnchecked(String name,IBinder token) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006519 return getContentProviderImpl(null, name, token, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 }
6521
6522 /**
6523 * Drop a content provider from a ProcessRecord's bookkeeping
6524 * @param cpr
6525 */
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006526 public void removeContentProvider(IBinder connection, boolean stable) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006527 enforceNotIsolatedCaller("removeContentProvider");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 synchronized (this) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006529 ContentProviderConnection conn;
6530 try {
6531 conn = (ContentProviderConnection)connection;
6532 } catch (ClassCastException e) {
6533 String msg ="removeContentProvider: " + connection
6534 + " not a ContentProviderConnection";
6535 Slog.w(TAG, msg);
6536 throw new IllegalArgumentException(msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006538 if (conn == null) {
6539 throw new NullPointerException("connection is null");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006540 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006541 if (decProviderCountLocked(conn, null, null, stable)) {
6542 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 }
6545 }
6546
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006547 public void removeContentProviderExternal(String name, IBinder token) {
6548 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY,
6549 "Do not have permission in call removeContentProviderExternal()");
6550 removeContentProviderExternalUnchecked(name, token);
6551 }
6552
6553 private void removeContentProviderExternalUnchecked(String name, IBinder token) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006554 synchronized (this) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006555 ContentProviderRecord cpr = mProviderMap.getProviderByName(name,
6556 Binder.getOrigCallingUser());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006557 if(cpr == null) {
6558 //remove from mProvidersByClass
Joe Onorato8a9b2202010-02-26 18:56:32 -08006559 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006560 return;
6561 }
6562
6563 //update content provider record entry info
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006564 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006565 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp,
6566 Binder.getOrigCallingUser());
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006567 if (localCpr.hasExternalProcessHandles()) {
6568 if (localCpr.removeExternalProcessHandleLocked(token)) {
6569 updateOomAdjLocked();
6570 } else {
6571 Slog.e(TAG, "Attmpt to remove content provider " + localCpr
6572 + " with no external reference for token: "
6573 + token + ".");
6574 }
6575 } else {
6576 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr
6577 + " with no external references.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 }
6580 }
6581
6582 public final void publishContentProviders(IApplicationThread caller,
6583 List<ContentProviderHolder> providers) {
6584 if (providers == null) {
6585 return;
6586 }
6587
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006588 enforceNotIsolatedCaller("publishContentProviders");
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006589 synchronized (this) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006590 final ProcessRecord r = getRecordForAppLocked(caller);
Amith Yamasani742a6712011-05-04 14:49:28 -07006591 if (DEBUG_MU)
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006592 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006593 if (r == null) {
6594 throw new SecurityException(
6595 "Unable to find app for caller " + caller
6596 + " (pid=" + Binder.getCallingPid()
6597 + ") when publishing content providers");
6598 }
6599
6600 final long origId = Binder.clearCallingIdentity();
6601
6602 final int N = providers.size();
6603 for (int i=0; i<N; i++) {
6604 ContentProviderHolder src = providers.get(i);
6605 if (src == null || src.info == null || src.provider == null) {
6606 continue;
6607 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07006608 ContentProviderRecord dst = r.pubProviders.get(src.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006609 if (DEBUG_MU)
6610 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006611 if (dst != null) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07006612 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name);
Amith Yamasani742a6712011-05-04 14:49:28 -07006613 mProviderMap.putProviderByClass(comp, dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 String names[] = dst.info.authority.split(";");
6615 for (int j = 0; j < names.length; j++) {
Amith Yamasani742a6712011-05-04 14:49:28 -07006616 mProviderMap.putProviderByName(names[j], dst);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 }
6618
6619 int NL = mLaunchingProviders.size();
6620 int j;
6621 for (j=0; j<NL; j++) {
6622 if (mLaunchingProviders.get(j) == dst) {
6623 mLaunchingProviders.remove(j);
6624 j--;
6625 NL--;
6626 }
6627 }
6628 synchronized (dst) {
6629 dst.provider = src.provider;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -07006630 dst.proc = r;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 dst.notifyAll();
6632 }
6633 updateOomAdjLocked(r);
6634 }
6635 }
6636
6637 Binder.restoreCallingIdentity(origId);
6638 }
6639 }
6640
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006641 public boolean refContentProvider(IBinder connection, int stable, int unstable) {
6642 ContentProviderConnection conn;
6643 try {
6644 conn = (ContentProviderConnection)connection;
6645 } catch (ClassCastException e) {
6646 String msg ="refContentProvider: " + connection
6647 + " not a ContentProviderConnection";
6648 Slog.w(TAG, msg);
6649 throw new IllegalArgumentException(msg);
6650 }
6651 if (conn == null) {
6652 throw new NullPointerException("connection is null");
6653 }
6654
6655 synchronized (this) {
6656 if (stable > 0) {
6657 conn.numStableIncs += stable;
6658 }
6659 stable = conn.stableCount + stable;
6660 if (stable < 0) {
6661 throw new IllegalStateException("stableCount < 0: " + stable);
6662 }
6663
6664 if (unstable > 0) {
6665 conn.numUnstableIncs += unstable;
6666 }
6667 unstable = conn.unstableCount + unstable;
6668 if (unstable < 0) {
6669 throw new IllegalStateException("unstableCount < 0: " + unstable);
6670 }
6671
6672 if ((stable+unstable) <= 0) {
6673 throw new IllegalStateException("ref counts can't go to zero here: stable="
6674 + stable + " unstable=" + unstable);
6675 }
6676 conn.stableCount = stable;
6677 conn.unstableCount = unstable;
6678 return !conn.dead;
6679 }
6680 }
6681
6682 public void unstableProviderDied(IBinder connection) {
6683 ContentProviderConnection conn;
6684 try {
6685 conn = (ContentProviderConnection)connection;
6686 } catch (ClassCastException e) {
6687 String msg ="refContentProvider: " + connection
6688 + " not a ContentProviderConnection";
6689 Slog.w(TAG, msg);
6690 throw new IllegalArgumentException(msg);
6691 }
6692 if (conn == null) {
6693 throw new NullPointerException("connection is null");
6694 }
6695
6696 // Safely retrieve the content provider associated with the connection.
6697 IContentProvider provider;
6698 synchronized (this) {
6699 provider = conn.provider.provider;
6700 }
6701
6702 if (provider == null) {
6703 // Um, yeah, we're way ahead of you.
6704 return;
6705 }
6706
6707 // Make sure the caller is being honest with us.
6708 if (provider.asBinder().pingBinder()) {
6709 // Er, no, still looks good to us.
6710 synchronized (this) {
6711 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid()
6712 + " says " + conn + " died, but we don't agree");
6713 return;
6714 }
6715 }
6716
6717 // Well look at that! It's dead!
6718 synchronized (this) {
6719 if (conn.provider.provider != provider) {
6720 // But something changed... good enough.
6721 return;
6722 }
6723
6724 ProcessRecord proc = conn.provider.proc;
6725 if (proc == null || proc.thread == null) {
6726 // Seems like the process is already cleaned up.
6727 return;
6728 }
6729
6730 // As far as we're concerned, this is just like receiving a
6731 // death notification... just a bit prematurely.
6732 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid
6733 + ") early provider death");
Dianne Hackbornbd145db2012-06-05 16:20:46 -07006734 final long ident = Binder.clearCallingIdentity();
6735 try {
6736 appDiedLocked(proc, proc.pid, proc.thread);
6737 } finally {
6738 Binder.restoreCallingIdentity(ident);
6739 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -07006740 }
6741 }
6742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006743 public static final void installSystemProviders() {
Jeff Brown10e89712011-07-08 18:52:57 -07006744 List<ProviderInfo> providers;
Josh Bartel2ecce342010-02-25 10:55:48 -06006745 synchronized (mSelf) {
6746 ProcessRecord app = mSelf.mProcessNames.get("system", Process.SYSTEM_UID);
6747 providers = mSelf.generateApplicationProvidersLocked(app);
Dianne Hackborn5c83a5f2010-03-12 16:46:46 -08006748 if (providers != null) {
6749 for (int i=providers.size()-1; i>=0; i--) {
6750 ProviderInfo pi = (ProviderInfo)providers.get(i);
6751 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
6752 Slog.w(TAG, "Not installing system proc provider " + pi.name
6753 + ": not system .apk");
6754 providers.remove(i);
6755 }
Dianne Hackbornc3b91fd2010-02-23 17:25:30 -08006756 }
6757 }
6758 }
Josh Bartel2ecce342010-02-25 10:55:48 -06006759 if (providers != null) {
6760 mSystemThread.installSystemProviders(providers);
6761 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -08006762
6763 mSelf.mCoreSettingsObserver = new CoreSettingsObserver(mSelf);
Mark Brophyc6350272011-08-05 16:16:39 +01006764
6765 mSelf.mUsageStatsService.monitorPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 }
6767
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006768 /**
6769 * Allows app to retrieve the MIME type of a URI without having permission
6770 * to access its content provider.
6771 *
6772 * CTS tests for this functionality can be run with "runtest cts-appsecurity".
6773 *
6774 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/
6775 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java
6776 */
6777 public String getProviderMimeType(Uri uri) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006778 enforceNotIsolatedCaller("getProviderMimeType");
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006779 final String name = uri.getAuthority();
6780 final long ident = Binder.clearCallingIdentity();
6781 ContentProviderHolder holder = null;
6782
6783 try {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006784 holder = getContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006785 if (holder != null) {
6786 return holder.provider.getType(uri);
6787 }
6788 } catch (RemoteException e) {
6789 Log.w(TAG, "Content provider dead retrieving " + uri, e);
6790 return null;
6791 } finally {
6792 if (holder != null) {
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006793 removeContentProviderExternalUnchecked(name, null);
Dianne Hackborncca1f0e2010-09-26 18:34:53 -07006794 }
6795 Binder.restoreCallingIdentity(ident);
6796 }
6797
6798 return null;
6799 }
6800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 // =========================================================
6802 // GLOBAL MANAGEMENT
6803 // =========================================================
6804
6805 final ProcessRecord newProcessRecordLocked(IApplicationThread thread,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006806 ApplicationInfo info, String customProcess, boolean isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006807 String proc = customProcess != null ? customProcess : info.processName;
6808 BatteryStatsImpl.Uid.Proc ps = null;
6809 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006810 int uid = info.uid;
6811 if (isolated) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006812 int userId = UserHandle.getUserId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006813 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1;
6814 uid = 0;
6815 while (true) {
6816 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID
6817 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) {
6818 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID;
6819 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006820 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006821 mNextIsolatedProcessUid++;
6822 if (mIsolatedProcesses.indexOfKey(uid) < 0) {
6823 // No process for this uid, use it.
6824 break;
6825 }
6826 stepsLeft--;
6827 if (stepsLeft <= 0) {
6828 return null;
6829 }
6830 }
6831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006832 synchronized (stats) {
6833 ps = stats.getProcessStatsLocked(info.uid, proc);
6834 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006835 return new ProcessRecord(ps, thread, info, proc, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 }
6837
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006838 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated) {
6839 ProcessRecord app;
6840 if (!isolated) {
6841 app = getProcessRecordLocked(info.processName, info.uid);
6842 } else {
6843 app = null;
6844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845
6846 if (app == null) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08006847 app = newProcessRecordLocked(null, info, null, isolated);
6848 mProcessNames.put(info.processName, app.uid, app);
6849 if (isolated) {
6850 mIsolatedProcesses.put(app.uid, app);
6851 }
Dianne Hackborndd71fc82009-12-16 19:24:32 -08006852 updateLruProcessLocked(app, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006853 }
6854
Dianne Hackborne7f97212011-02-24 14:40:20 -08006855 // This package really, really can not be stopped.
6856 try {
6857 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07006858 info.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -08006859 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08006860 } catch (IllegalArgumentException e) {
6861 Slog.w(TAG, "Failed trying to unstop package "
6862 + info.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08006863 }
6864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006865 if ((info.flags&(ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT))
6866 == (ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT)) {
6867 app.persistent = true;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07006868 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006869 }
6870 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) {
6871 mPersistentStartingProcesses.add(app);
6872 startProcessLocked(app, "added application", app.processName);
6873 }
6874
6875 return app;
6876 }
6877
6878 public void unhandledBack() {
6879 enforceCallingPermission(android.Manifest.permission.FORCE_BACK,
6880 "unhandledBack()");
6881
6882 synchronized(this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006883 int count = mMainStack.mHistory.size();
Joe Onorato8a9b2202010-02-26 18:56:32 -08006884 if (DEBUG_SWITCH) Slog.d(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006885 TAG, "Performing unhandledBack(): stack size = " + count);
6886 if (count > 1) {
6887 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006888 mMainStack.finishActivityLocked((ActivityRecord)mMainStack.mHistory.get(count-1),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006889 count-1, Activity.RESULT_CANCELED, null, "unhandled-back");
6890 Binder.restoreCallingIdentity(origId);
6891 }
6892 }
6893 }
6894
6895 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08006896 enforceNotIsolatedCaller("openContentUri");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006897 String name = uri.getAuthority();
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006898 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006899 ParcelFileDescriptor pfd = null;
6900 if (cph != null) {
6901 // We record the binder invoker's uid in thread-local storage before
6902 // going to the content provider to open the file. Later, in the code
6903 // that handles all permissions checks, we look for this uid and use
6904 // that rather than the Activity Manager's own uid. The effect is that
6905 // we do the check against the caller's permissions even though it looks
6906 // to the content provider like the Activity Manager itself is making
6907 // the request.
6908 sCallerIdentity.set(new Identity(
6909 Binder.getCallingPid(), Binder.getCallingUid()));
6910 try {
6911 pfd = cph.provider.openFile(uri, "r");
6912 } catch (FileNotFoundException e) {
6913 // do nothing; pfd will be returned null
6914 } finally {
6915 // Ensure that whatever happens, we clean up the identity state
6916 sCallerIdentity.remove();
6917 }
6918
6919 // We've got the fd now, so we're done with the provider.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -08006920 removeContentProviderExternalUnchecked(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006921 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006922 Slog.d(TAG, "Failed to get provider for authority '" + name + "'");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006923 }
6924 return pfd;
6925 }
6926
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006927 // Actually is sleeping or shutting down or whatever else in the future
6928 // is an inactive state.
6929 public boolean isSleeping() {
6930 return mSleeping || mShuttingDown;
6931 }
6932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006933 public void goingToSleep() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006934 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
6935 != PackageManager.PERMISSION_GRANTED) {
6936 throw new SecurityException("Requires permission "
6937 + android.Manifest.permission.DEVICE_POWER);
6938 }
6939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006940 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006941 mWentToSleep = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006942 updateEventDispatchingLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006943
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006944 if (!mSleeping) {
6945 mSleeping = true;
6946 mMainStack.stopIfSleepingLocked();
Dianne Hackborn9adb9c32010-08-13 14:09:56 -07006947
Dianne Hackbornff5b1582012-04-12 17:24:07 -07006948 // Initialize the wake times of all processes.
6949 checkExcessivePowerUsageLocked(false);
6950 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6951 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG);
6952 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY);
6953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006954 }
6955 }
6956
Dianne Hackborn55280a92009-05-07 15:53:46 -07006957 public boolean shutdown(int timeout) {
6958 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN)
6959 != PackageManager.PERMISSION_GRANTED) {
6960 throw new SecurityException("Requires permission "
6961 + android.Manifest.permission.SHUTDOWN);
6962 }
6963
6964 boolean timedout = false;
6965
6966 synchronized(this) {
6967 mShuttingDown = true;
Jeff Brownc042ee22012-05-08 13:03:42 -07006968 updateEventDispatchingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006969
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006970 if (mMainStack.mResumedActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006971 mMainStack.stopIfSleepingLocked();
Dianne Hackborn55280a92009-05-07 15:53:46 -07006972 final long endTime = System.currentTimeMillis() + timeout;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07006973 while (mMainStack.mResumedActivity != null
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08006974 || mMainStack.mPausingActivity != null) {
Dianne Hackborn55280a92009-05-07 15:53:46 -07006975 long delay = endTime - System.currentTimeMillis();
6976 if (delay <= 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08006977 Slog.w(TAG, "Activity manager shutdown timed out");
Dianne Hackborn55280a92009-05-07 15:53:46 -07006978 timedout = true;
6979 break;
6980 }
6981 try {
6982 this.wait();
6983 } catch (InterruptedException e) {
6984 }
6985 }
6986 }
6987 }
6988
6989 mUsageStatsService.shutdown();
6990 mBatteryStatsService.shutdown();
6991
6992 return timedout;
6993 }
6994
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08006995 public final void activitySlept(IBinder token) {
6996 if (localLOGV) Slog.v(
6997 TAG, "Activity slept: token=" + token);
6998
6999 ActivityRecord r = null;
7000
7001 final long origId = Binder.clearCallingIdentity();
7002
7003 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007004 r = mMainStack.isInStackLocked(token);
7005 if (r != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08007006 mMainStack.activitySleptLocked(r);
7007 }
7008 }
7009
7010 Binder.restoreCallingIdentity(origId);
7011 }
7012
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007013 private void comeOutOfSleepIfNeededLocked() {
7014 if (!mWentToSleep && !mLockScreenShown) {
7015 if (mSleeping) {
7016 mSleeping = false;
7017 mMainStack.awakeFromSleepingLocked();
7018 mMainStack.resumeTopActivityLocked(null);
7019 }
7020 }
7021 }
7022
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007023 public void wakingUp() {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007024 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7025 != PackageManager.PERMISSION_GRANTED) {
7026 throw new SecurityException("Requires permission "
7027 + android.Manifest.permission.DEVICE_POWER);
7028 }
7029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007030 synchronized(this) {
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007031 mWentToSleep = false;
Jeff Brownc042ee22012-05-08 13:03:42 -07007032 updateEventDispatchingLocked();
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007033 comeOutOfSleepIfNeededLocked();
7034 }
7035 }
7036
Jeff Brownc042ee22012-05-08 13:03:42 -07007037 private void updateEventDispatchingLocked() {
7038 mWindowManager.setEventDispatching(mBooted && !mWentToSleep && !mShuttingDown);
7039 }
7040
Dianne Hackbornff5b1582012-04-12 17:24:07 -07007041 public void setLockScreenShown(boolean shown) {
7042 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER)
7043 != PackageManager.PERMISSION_GRANTED) {
7044 throw new SecurityException("Requires permission "
7045 + android.Manifest.permission.DEVICE_POWER);
7046 }
7047
7048 synchronized(this) {
7049 mLockScreenShown = shown;
7050 comeOutOfSleepIfNeededLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007051 }
7052 }
7053
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007054 public void stopAppSwitches() {
7055 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7056 != PackageManager.PERMISSION_GRANTED) {
7057 throw new SecurityException("Requires permission "
7058 + android.Manifest.permission.STOP_APP_SWITCHES);
7059 }
7060
7061 synchronized(this) {
7062 mAppSwitchesAllowedTime = SystemClock.uptimeMillis()
7063 + APP_SWITCH_DELAY_TIME;
7064 mDidAppSwitch = false;
7065 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7066 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG);
7067 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME);
7068 }
7069 }
7070
7071 public void resumeAppSwitches() {
7072 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES)
7073 != PackageManager.PERMISSION_GRANTED) {
7074 throw new SecurityException("Requires permission "
7075 + android.Manifest.permission.STOP_APP_SWITCHES);
7076 }
7077
7078 synchronized(this) {
7079 // Note that we don't execute any pending app switches... we will
7080 // let those wait until either the timeout, or the next start
7081 // activity request.
7082 mAppSwitchesAllowedTime = 0;
7083 }
7084 }
7085
7086 boolean checkAppSwitchAllowedLocked(int callingPid, int callingUid,
7087 String name) {
7088 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) {
7089 return true;
7090 }
7091
7092 final int perm = checkComponentPermission(
7093 android.Manifest.permission.STOP_APP_SWITCHES, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08007094 callingUid, -1, true);
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007095 if (perm == PackageManager.PERMISSION_GRANTED) {
7096 return true;
7097 }
7098
Joe Onorato8a9b2202010-02-26 18:56:32 -08007099 Slog.w(TAG, name + " request from " + callingUid + " stopped");
Dianne Hackborn95fc68f2009-05-19 18:37:45 -07007100 return false;
7101 }
7102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007103 public void setDebugApp(String packageName, boolean waitForDebugger,
7104 boolean persistent) {
7105 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP,
7106 "setDebugApp()");
7107
7108 // Note that this is not really thread safe if there are multiple
7109 // callers into it at the same time, but that's not a situation we
7110 // care about.
7111 if (persistent) {
7112 final ContentResolver resolver = mContext.getContentResolver();
7113 Settings.System.putString(
7114 resolver, Settings.System.DEBUG_APP,
7115 packageName);
7116 Settings.System.putInt(
7117 resolver, Settings.System.WAIT_FOR_DEBUGGER,
7118 waitForDebugger ? 1 : 0);
7119 }
7120
7121 synchronized (this) {
7122 if (!persistent) {
7123 mOrigDebugApp = mDebugApp;
7124 mOrigWaitForDebugger = mWaitForDebugger;
7125 }
7126 mDebugApp = packageName;
7127 mWaitForDebugger = waitForDebugger;
7128 mDebugTransient = !persistent;
7129 if (packageName != null) {
7130 final long origId = Binder.clearCallingIdentity();
Amith Yamasani483f3b02012-03-13 16:08:00 -07007131 forceStopPackageLocked(packageName, -1, false, false, true, true, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007132 Binder.restoreCallingIdentity(origId);
7133 }
7134 }
7135 }
7136
Siva Velusamy92a8b222012-03-09 16:24:04 -08007137 void setOpenGlTraceApp(ApplicationInfo app, String processName) {
7138 synchronized (this) {
7139 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7140 if (!isDebuggable) {
7141 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7142 throw new SecurityException("Process not debuggable: " + app.packageName);
7143 }
7144 }
7145
7146 mOpenGlTraceApp = processName;
7147 }
7148 }
7149
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07007150 void setProfileApp(ApplicationInfo app, String processName, String profileFile,
7151 ParcelFileDescriptor profileFd, boolean autoStopProfiler) {
7152 synchronized (this) {
7153 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
7154 if (!isDebuggable) {
7155 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
7156 throw new SecurityException("Process not debuggable: " + app.packageName);
7157 }
7158 }
7159 mProfileApp = processName;
7160 mProfileFile = profileFile;
7161 if (mProfileFd != null) {
7162 try {
7163 mProfileFd.close();
7164 } catch (IOException e) {
7165 }
7166 mProfileFd = null;
7167 }
7168 mProfileFd = profileFd;
7169 mProfileType = 0;
7170 mAutoStopProfiler = autoStopProfiler;
7171 }
7172 }
7173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007174 public void setAlwaysFinish(boolean enabled) {
7175 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH,
7176 "setAlwaysFinish()");
7177
7178 Settings.System.putInt(
7179 mContext.getContentResolver(),
7180 Settings.System.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0);
7181
7182 synchronized (this) {
7183 mAlwaysFinishActivities = enabled;
7184 }
7185 }
7186
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007187 public void setActivityController(IActivityController controller) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007188 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007189 "setActivityController()");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07007191 mController = controller;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007192 }
7193 }
7194
Dianne Hackborn9327f4f2010-01-29 10:38:29 -08007195 public boolean isUserAMonkey() {
7196 // For now the fact that there is a controller implies
7197 // we have a monkey.
7198 synchronized (this) {
7199 return mController != null;
7200 }
7201 }
7202
Jeff Sharkeya4620792011-05-20 15:29:23 -07007203 public void registerProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007204 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER,
7205 "registerProcessObserver()");
7206 synchronized (this) {
7207 mProcessObservers.register(observer);
7208 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007209 }
7210
7211 public void unregisterProcessObserver(IProcessObserver observer) {
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -08007212 synchronized (this) {
7213 mProcessObservers.unregister(observer);
7214 }
Jeff Sharkeya4620792011-05-20 15:29:23 -07007215 }
7216
Daniel Sandler69a48172010-06-23 16:29:36 -04007217 public void setImmersive(IBinder token, boolean immersive) {
7218 synchronized(this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007219 ActivityRecord r = mMainStack.isInStackLocked(token);
7220 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007221 throw new IllegalArgumentException();
7222 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007223 r.immersive = immersive;
7224 }
7225 }
7226
7227 public boolean isImmersive(IBinder token) {
7228 synchronized (this) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07007229 ActivityRecord r = mMainStack.isInStackLocked(token);
7230 if (r == null) {
Daniel Sandler69a48172010-06-23 16:29:36 -04007231 throw new IllegalArgumentException();
7232 }
Daniel Sandler69a48172010-06-23 16:29:36 -04007233 return r.immersive;
7234 }
7235 }
7236
7237 public boolean isTopActivityImmersive() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08007238 enforceNotIsolatedCaller("startActivity");
Daniel Sandler69a48172010-06-23 16:29:36 -04007239 synchronized (this) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007240 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Daniel Sandler69a48172010-06-23 16:29:36 -04007241 return (r != null) ? r.immersive : false;
7242 }
7243 }
7244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007245 public final void enterSafeMode() {
7246 synchronized(this) {
7247 // It only makes sense to do this before the system is ready
7248 // and started launching other packages.
7249 if (!mSystemReady) {
7250 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007251 AppGlobals.getPackageManager().enterSafeMode();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007252 } catch (RemoteException e) {
7253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007254 }
7255 }
7256 }
7257
Jeff Brownb09abc12011-01-13 21:08:27 -08007258 public final void showSafeModeOverlay() {
7259 View v = LayoutInflater.from(mContext).inflate(
7260 com.android.internal.R.layout.safe_mode, null);
7261 WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
7262 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY;
7263 lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
7264 lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
Fabrice Di Meglioaac0d4e2012-07-19 19:21:26 -07007265 lp.gravity = Gravity.BOTTOM | Gravity.START;
Jeff Brownb09abc12011-01-13 21:08:27 -08007266 lp.format = v.getBackground().getOpacity();
7267 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
7268 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
7269 ((WindowManager)mContext.getSystemService(
7270 Context.WINDOW_SERVICE)).addView(v, lp);
7271 }
7272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007273 public void noteWakeupAlarm(IIntentSender sender) {
7274 if (!(sender instanceof PendingIntentRecord)) {
7275 return;
7276 }
7277 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
7278 synchronized (stats) {
7279 if (mBatteryStatsService.isOnBattery()) {
7280 mBatteryStatsService.enforceCallingPermission();
7281 PendingIntentRecord rec = (PendingIntentRecord)sender;
7282 int MY_UID = Binder.getCallingUid();
7283 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid;
7284 BatteryStatsImpl.Uid.Pkg pkg =
7285 stats.getPackageStatsLocked(uid, rec.key.packageName);
7286 pkg.incWakeupsLocked();
7287 }
7288 }
7289 }
7290
Dianne Hackborn64825172011-03-02 21:32:58 -08007291 public boolean killPids(int[] pids, String pReason, boolean secure) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007292 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007293 throw new SecurityException("killPids only available to the system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007294 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007295 String reason = (pReason == null) ? "Unknown" : pReason;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 // XXX Note: don't acquire main activity lock here, because the window
7297 // manager calls in with its locks held.
7298
7299 boolean killed = false;
7300 synchronized (mPidsSelfLocked) {
7301 int[] types = new int[pids.length];
7302 int worstType = 0;
7303 for (int i=0; i<pids.length; i++) {
7304 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7305 if (proc != null) {
7306 int type = proc.setAdj;
7307 types[i] = type;
7308 if (type > worstType) {
7309 worstType = type;
7310 }
7311 }
7312 }
7313
Dianne Hackborn64825172011-03-02 21:32:58 -08007314 // If the worst oom_adj is somewhere in the hidden proc LRU range,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007315 // then constrain it so we will kill all hidden procs.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007316 if (worstType < ProcessList.HIDDEN_APP_MAX_ADJ
7317 && worstType > ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07007318 worstType = ProcessList.HIDDEN_APP_MIN_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007319 }
Dianne Hackborn64825172011-03-02 21:32:58 -08007320
7321 // If this is not a secure call, don't let it kill processes that
7322 // are important.
Dianne Hackborne02c88a2011-10-28 13:58:15 -07007323 if (!secure && worstType < ProcessList.SERVICE_ADJ) {
7324 worstType = ProcessList.SERVICE_ADJ;
Dianne Hackborn64825172011-03-02 21:32:58 -08007325 }
7326
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007327 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007328 for (int i=0; i<pids.length; i++) {
7329 ProcessRecord proc = mPidsSelfLocked.get(pids[i]);
7330 if (proc == null) {
7331 continue;
7332 }
7333 int adj = proc.setAdj;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007334 if (adj >= worstType && !proc.killedBackground) {
Dianne Hackborn8633e682010-04-22 16:03:41 -07007335 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07007336 EventLog.writeEvent(EventLogTags.AM_KILL, proc.pid,
7337 proc.processName, adj, reason);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007338 killed = true;
Dianne Hackborn906497c2010-05-10 15:57:38 -07007339 proc.killedBackground = true;
7340 Process.killProcessQuiet(pids[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007341 }
7342 }
7343 }
7344 return killed;
7345 }
Jeff Sharkeyb9a07012012-03-22 17:00:04 -07007346
7347 @Override
7348 public boolean killProcessesBelowForeground(String reason) {
7349 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7350 throw new SecurityException("killProcessesBelowForeground() only available to system");
7351 }
7352
7353 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason);
7354 }
7355
7356 private boolean killProcessesBelowAdj(int belowAdj, String reason) {
7357 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
7358 throw new SecurityException("killProcessesBelowAdj() only available to system");
7359 }
7360
7361 boolean killed = false;
7362 synchronized (mPidsSelfLocked) {
7363 final int size = mPidsSelfLocked.size();
7364 for (int i = 0; i < size; i++) {
7365 final int pid = mPidsSelfLocked.keyAt(i);
7366 final ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7367 if (proc == null) continue;
7368
7369 final int adj = proc.setAdj;
7370 if (adj > belowAdj && !proc.killedBackground) {
7371 Slog.w(TAG, "Killing " + proc + " (adj " + adj + "): " + reason);
7372 EventLog.writeEvent(
7373 EventLogTags.AM_KILL, proc.pid, proc.processName, adj, reason);
7374 killed = true;
7375 proc.killedBackground = true;
7376 Process.killProcessQuiet(pid);
7377 }
7378 }
7379 }
7380 return killed;
7381 }
7382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007383 public final void startRunning(String pkg, String cls, String action,
7384 String data) {
7385 synchronized(this) {
7386 if (mStartRunning) {
7387 return;
7388 }
7389 mStartRunning = true;
7390 mTopComponent = pkg != null && cls != null
7391 ? new ComponentName(pkg, cls) : null;
7392 mTopAction = action != null ? action : Intent.ACTION_MAIN;
7393 mTopData = data;
7394 if (!mSystemReady) {
7395 return;
7396 }
7397 }
7398
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007399 systemReady(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007400 }
7401
7402 private void retrieveSettings() {
7403 final ContentResolver resolver = mContext.getContentResolver();
7404 String debugApp = Settings.System.getString(
7405 resolver, Settings.System.DEBUG_APP);
7406 boolean waitForDebugger = Settings.System.getInt(
7407 resolver, Settings.System.WAIT_FOR_DEBUGGER, 0) != 0;
7408 boolean alwaysFinishActivities = Settings.System.getInt(
7409 resolver, Settings.System.ALWAYS_FINISH_ACTIVITIES, 0) != 0;
7410
7411 Configuration configuration = new Configuration();
7412 Settings.System.getConfiguration(resolver, configuration);
7413
7414 synchronized (this) {
7415 mDebugApp = mOrigDebugApp = debugApp;
7416 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger;
7417 mAlwaysFinishActivities = alwaysFinishActivities;
7418 // This happens before any activities are started, so we can
7419 // change mConfiguration in-place.
Dianne Hackborn813075a62011-11-14 17:45:19 -08007420 updateConfigurationLocked(configuration, null, false, true);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007421 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Initial config: " + mConfiguration);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007422 }
7423 }
7424
7425 public boolean testIsSystemReady() {
7426 // no need to synchronize(this) just to read & return the value
7427 return mSystemReady;
7428 }
7429
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007430 private static File getCalledPreBootReceiversFile() {
7431 File dataDir = Environment.getDataDirectory();
7432 File systemDir = new File(dataDir, "system");
7433 File fname = new File(systemDir, "called_pre_boots.dat");
7434 return fname;
7435 }
Dianne Hackborn661cd522011-08-22 00:26:20 -07007436
7437 static final int LAST_DONE_VERSION = 10000;
7438
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007439 private static ArrayList<ComponentName> readLastDonePreBootReceivers() {
7440 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>();
7441 File file = getCalledPreBootReceiversFile();
7442 FileInputStream fis = null;
7443 try {
7444 fis = new FileInputStream(file);
7445 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007446 int fvers = dis.readInt();
7447 if (fvers == LAST_DONE_VERSION) {
7448 String vers = dis.readUTF();
7449 String codename = dis.readUTF();
7450 String build = dis.readUTF();
7451 if (android.os.Build.VERSION.RELEASE.equals(vers)
7452 && android.os.Build.VERSION.CODENAME.equals(codename)
7453 && android.os.Build.VERSION.INCREMENTAL.equals(build)) {
7454 int num = dis.readInt();
7455 while (num > 0) {
7456 num--;
7457 String pkg = dis.readUTF();
7458 String cls = dis.readUTF();
7459 lastDoneReceivers.add(new ComponentName(pkg, cls));
7460 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007461 }
7462 }
7463 } catch (FileNotFoundException e) {
7464 } catch (IOException e) {
7465 Slog.w(TAG, "Failure reading last done pre-boot receivers", e);
7466 } finally {
7467 if (fis != null) {
7468 try {
7469 fis.close();
7470 } catch (IOException e) {
7471 }
7472 }
7473 }
7474 return lastDoneReceivers;
7475 }
7476
7477 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) {
7478 File file = getCalledPreBootReceiversFile();
7479 FileOutputStream fos = null;
7480 DataOutputStream dos = null;
7481 try {
7482 Slog.i(TAG, "Writing new set of last done pre-boot receivers...");
7483 fos = new FileOutputStream(file);
7484 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048));
Dianne Hackborn661cd522011-08-22 00:26:20 -07007485 dos.writeInt(LAST_DONE_VERSION);
7486 dos.writeUTF(android.os.Build.VERSION.RELEASE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007487 dos.writeUTF(android.os.Build.VERSION.CODENAME);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007488 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007489 dos.writeInt(list.size());
7490 for (int i=0; i<list.size(); i++) {
7491 dos.writeUTF(list.get(i).getPackageName());
7492 dos.writeUTF(list.get(i).getClassName());
7493 }
7494 } catch (IOException e) {
7495 Slog.w(TAG, "Failure writing last done pre-boot receivers", e);
7496 file.delete();
7497 } finally {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07007498 FileUtils.sync(fos);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007499 if (dos != null) {
7500 try {
7501 dos.close();
7502 } catch (IOException e) {
7503 // TODO Auto-generated catch block
7504 e.printStackTrace();
7505 }
7506 }
7507 }
7508 }
7509
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007510 public void systemReady(final Runnable goingCallback) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007511 synchronized(this) {
7512 if (mSystemReady) {
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007513 if (goingCallback != null) goingCallback.run();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007514 return;
7515 }
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007516
7517 // Check to see if there are any update receivers to run.
7518 if (!mDidUpdate) {
7519 if (mWaitingUpdate) {
7520 return;
7521 }
7522 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
7523 List<ResolveInfo> ris = null;
7524 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007525 ris = AppGlobals.getPackageManager().queryIntentReceivers(
Amith Yamasani483f3b02012-03-13 16:08:00 -07007526 intent, null, 0, 0);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007527 } catch (RemoteException e) {
7528 }
7529 if (ris != null) {
7530 for (int i=ris.size()-1; i>=0; i--) {
7531 if ((ris.get(i).activityInfo.applicationInfo.flags
7532 &ApplicationInfo.FLAG_SYSTEM) == 0) {
7533 ris.remove(i);
7534 }
7535 }
7536 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007537
7538 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
7539
7540 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007541 for (int i=0; i<ris.size(); i++) {
7542 ActivityInfo ai = ris.get(i).activityInfo;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007543 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7544 if (lastDoneReceivers.contains(comp)) {
7545 ris.remove(i);
7546 i--;
7547 }
7548 }
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07007549
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007550 for (int i=0; i<ris.size(); i++) {
7551 ActivityInfo ai = ris.get(i).activityInfo;
7552 ComponentName comp = new ComponentName(ai.packageName, ai.name);
7553 doneReceivers.add(comp);
7554 intent.setComponent(comp);
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007555 IIntentReceiver finisher = null;
Dianne Hackbornd6847842010-01-12 18:14:19 -08007556 if (i == ris.size()-1) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007557 finisher = new IIntentReceiver.Stub() {
7558 public void performReceive(Intent intent, int resultCode,
Dianne Hackborn68d881c2009-10-05 13:58:17 -07007559 String data, Bundle extras, boolean ordered,
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007560 boolean sticky) {
7561 // The raw IIntentReceiver interface is called
7562 // with the AM lock held, so redispatch to
7563 // execute our code without the lock.
7564 mHandler.post(new Runnable() {
7565 public void run() {
7566 synchronized (ActivityManagerService.this) {
7567 mDidUpdate = true;
7568 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007569 writeLastDonePreBootReceivers(doneReceivers);
Dianne Hackborn661cd522011-08-22 00:26:20 -07007570 showBootMessage(mContext.getText(
7571 R.string.android_upgrading_complete),
7572 false);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07007573 systemReady(goingCallback);
7574 }
7575 });
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007576 }
7577 };
7578 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08007579 Slog.i(TAG, "Sending system update to: " + intent.getComponent());
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007580 // XXX also need to send this to stopped users(!!!)
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007581 broadcastIntentLocked(null, null, intent, null, finisher,
Amith Yamasani742a6712011-05-04 14:49:28 -07007582 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07007583 UserHandle.USER_ALL);
Dianne Hackbornd6847842010-01-12 18:14:19 -08007584 if (finisher != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007585 mWaitingUpdate = true;
7586 }
7587 }
7588 }
7589 if (mWaitingUpdate) {
7590 return;
7591 }
7592 mDidUpdate = true;
7593 }
7594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007595 mSystemReady = true;
7596 if (!mStartRunning) {
7597 return;
7598 }
7599 }
7600
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007601 ArrayList<ProcessRecord> procsToKill = null;
7602 synchronized(mPidsSelfLocked) {
7603 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
7604 ProcessRecord proc = mPidsSelfLocked.valueAt(i);
7605 if (!isAllowedWhileBooting(proc.info)){
7606 if (procsToKill == null) {
7607 procsToKill = new ArrayList<ProcessRecord>();
7608 }
7609 procsToKill.add(proc);
7610 }
7611 }
7612 }
7613
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007614 synchronized(this) {
7615 if (procsToKill != null) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007616 for (int i=procsToKill.size()-1; i>=0; i--) {
7617 ProcessRecord proc = procsToKill.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -08007618 Slog.i(TAG, "Removing system update proc: " + proc);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007619 removeProcessLocked(proc, true, false, "system update done");
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007620 }
7621 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007622
7623 // Now that we have cleaned up any update processes, we
7624 // are ready to start launching real processes and know that
7625 // we won't trample on them any more.
7626 mProcessesReady = true;
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007627 }
7628
Joe Onorato8a9b2202010-02-26 18:56:32 -08007629 Slog.i(TAG, "System now ready");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007630 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007631 SystemClock.uptimeMillis());
7632
7633 synchronized(this) {
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007634 // Make sure we have no pre-ready processes sitting around.
7635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
7637 ResolveInfo ri = mContext.getPackageManager()
7638 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),
Dianne Hackborn1655be42009-05-08 14:29:01 -07007639 STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007640 CharSequence errorMsg = null;
7641 if (ri != null) {
7642 ActivityInfo ai = ri.activityInfo;
7643 ApplicationInfo app = ai.applicationInfo;
7644 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7645 mTopAction = Intent.ACTION_FACTORY_TEST;
7646 mTopData = null;
7647 mTopComponent = new ComponentName(app.packageName,
7648 ai.name);
7649 } else {
7650 errorMsg = mContext.getResources().getText(
7651 com.android.internal.R.string.factorytest_not_system);
7652 }
7653 } else {
7654 errorMsg = mContext.getResources().getText(
7655 com.android.internal.R.string.factorytest_no_action);
7656 }
7657 if (errorMsg != null) {
7658 mTopAction = null;
7659 mTopData = null;
7660 mTopComponent = null;
7661 Message msg = Message.obtain();
7662 msg.what = SHOW_FACTORY_ERROR_MSG;
7663 msg.getData().putCharSequence("msg", errorMsg);
7664 mHandler.sendMessage(msg);
7665 }
7666 }
7667 }
7668
7669 retrieveSettings();
7670
Dianne Hackborna34f1ad2009-09-02 13:26:28 -07007671 if (goingCallback != null) goingCallback.run();
7672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007673 synchronized (this) {
7674 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
7675 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007676 List apps = AppGlobals.getPackageManager().
Dianne Hackborn1655be42009-05-08 14:29:01 -07007677 getPersistentApplications(STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 if (apps != null) {
7679 int N = apps.size();
7680 int i;
7681 for (i=0; i<N; i++) {
7682 ApplicationInfo info
7683 = (ApplicationInfo)apps.get(i);
7684 if (info != null &&
7685 !info.packageName.equals("android")) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007686 addAppLocked(info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 }
7688 }
7689 }
7690 } catch (RemoteException ex) {
7691 // pm is in same process, this will never happen.
7692 }
7693 }
7694
Dianne Hackborn9acc0302009-08-25 00:27:12 -07007695 // Start up initial activity.
7696 mBooting = true;
7697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007698 try {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07007699 if (AppGlobals.getPackageManager().hasSystemUidErrors()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007700 Message msg = Message.obtain();
7701 msg.what = SHOW_UID_ERROR_MSG;
7702 mHandler.sendMessage(msg);
7703 }
7704 } catch (RemoteException e) {
7705 }
7706
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007707 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 }
7709 }
7710
Dan Egnorb7f03672009-12-09 16:22:32 -08007711 private boolean makeAppCrashingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007712 String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007713 app.crashing = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007714 app.crashingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007715 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716 startAppProblemLocked(app);
7717 app.stopFreezingAllLocked();
7718 return handleAppCrashLocked(app);
7719 }
7720
Dan Egnorb7f03672009-12-09 16:22:32 -08007721 private void makeAppNotRespondingLocked(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007722 String activity, String shortMsg, String longMsg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007723 app.notResponding = true;
Dan Egnorb7f03672009-12-09 16:22:32 -08007724 app.notRespondingReport = generateProcessError(app,
Dan Egnor60d87622009-12-16 16:32:58 -08007725 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
7726 activity, shortMsg, longMsg, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007727 startAppProblemLocked(app);
7728 app.stopFreezingAllLocked();
7729 }
7730
7731 /**
7732 * Generate a process error record, suitable for attachment to a ProcessRecord.
7733 *
7734 * @param app The ProcessRecord in which the error occurred.
7735 * @param condition Crashing, Application Not Responding, etc. Values are defined in
7736 * ActivityManager.AppErrorStateInfo
Dan Egnor60d87622009-12-16 16:32:58 -08007737 * @param activity The activity associated with the crash, if known.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 * @param shortMsg Short message describing the crash.
7739 * @param longMsg Long message describing the crash.
Dan Egnorb7f03672009-12-09 16:22:32 -08007740 * @param stackTrace Full crash stack trace, may be null.
7741 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007742 * @return Returns a fully-formed AppErrorStateInfo record.
7743 */
7744 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
Dan Egnor60d87622009-12-16 16:32:58 -08007745 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007746 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
Dan Egnorb7f03672009-12-09 16:22:32 -08007747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 report.condition = condition;
7749 report.processName = app.processName;
7750 report.pid = app.pid;
7751 report.uid = app.info.uid;
Dan Egnor60d87622009-12-16 16:32:58 -08007752 report.tag = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753 report.shortMsg = shortMsg;
7754 report.longMsg = longMsg;
Dan Egnorb7f03672009-12-09 16:22:32 -08007755 report.stackTrace = stackTrace;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007756
7757 return report;
7758 }
7759
Dan Egnor42471dd2010-01-07 17:25:22 -08007760 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007761 synchronized (this) {
7762 app.crashing = false;
7763 app.crashingReport = null;
7764 app.notResponding = false;
7765 app.notRespondingReport = null;
7766 if (app.anrDialog == fromDialog) {
7767 app.anrDialog = null;
7768 }
7769 if (app.waitDialog == fromDialog) {
7770 app.waitDialog = null;
7771 }
7772 if (app.pid > 0 && app.pid != MY_PID) {
Dan Egnor42471dd2010-01-07 17:25:22 -08007773 handleAppCrashLocked(app);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007774 Slog.i(ActivityManagerService.TAG, "Killing " + app + ": user's request");
Dianne Hackborn8633e682010-04-22 16:03:41 -07007775 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
7776 app.processName, app.setAdj, "user's request after error");
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07007777 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 }
7780 }
Dan Egnor42471dd2010-01-07 17:25:22 -08007781
Dan Egnorb7f03672009-12-09 16:22:32 -08007782 private boolean handleAppCrashLocked(ProcessRecord app) {
Mike Lockwood86548c42011-09-13 17:21:46 -04007783 if (mHeadless) {
7784 Log.e(TAG, "handleAppCrashLocked: " + app.processName);
7785 return false;
7786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 long now = SystemClock.uptimeMillis();
7788
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007789 Long crashTime;
7790 if (!app.isolated) {
7791 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
7792 } else {
7793 crashTime = null;
7794 }
Dianne Hackborn7d608422011-08-07 16:24:18 -07007795 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007796 // This process loses!
Joe Onorato8a9b2202010-02-26 18:56:32 -08007797 Slog.w(TAG, "Process " + app.info.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007798 + " has crashed too many times: killing!");
Doug Zongker2bec3d42009-12-04 12:52:44 -08007799 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007800 app.info.processName, app.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007801 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) {
7802 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007803 if (r.app == app) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08007804 Slog.w(TAG, " Force finishing activity "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007806 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, null, "crashed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 }
7808 }
7809 if (!app.persistent) {
7810 // We don't want to start this process again until the user
7811 // explicitly does so... but for persistent process, we really
7812 // need to keep it running. If a persistent process is actually
7813 // repeatedly crashing, then badness for everyone.
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007814 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 app.info.processName);
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007816 if (!app.isolated) {
7817 // XXX We don't have a way to mark isolated processes
7818 // as bad, since they don't have a peristent identity.
7819 mBadProcesses.put(app.info.processName, app.uid, now);
7820 mProcessCrashTimes.remove(app.info.processName, app.uid);
7821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007822 app.bad = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007823 app.removed = true;
Dianne Hackborn130b0d22011-07-26 22:07:48 -07007824 // Don't let services in this process be restarted and potentially
7825 // annoy the user repeatedly. Unless it is persistent, since those
7826 // processes run critical code.
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -08007827 removeProcessLocked(app, false, false, "crash");
Dianne Hackborncb44d962011-03-10 17:02:27 -08007828 mMainStack.resumeTopActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007829 return false;
7830 }
Dianne Hackborncb44d962011-03-10 17:02:27 -08007831 mMainStack.resumeTopActivityLocked(null);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007832 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007833 ActivityRecord r = mMainStack.topRunningActivityLocked(null);
Kevin Hester-Chowd87a9be2012-03-05 08:01:00 -08007834 if (r != null && r.app == app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007835 // If the top running activity is from this crashing
7836 // process, then terminate it to avoid getting in a loop.
7837 Slog.w(TAG, " Force finishing activity "
7838 + r.intent.getComponent().flattenToShortString());
Dianne Hackbornbe707852011-11-11 14:32:10 -08007839 int index = mMainStack.indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007840 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007841 Activity.RESULT_CANCELED, null, "crashed");
Dianne Hackborn070783f2010-12-29 16:46:28 -08007842 // Also terminate any activities below it that aren't yet
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007843 // stopped, to avoid a situation where one will get
7844 // re-start our crashing activity once it gets resumed again.
7845 index--;
7846 if (index >= 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007847 r = (ActivityRecord)mMainStack.mHistory.get(index);
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007848 if (r.state == ActivityState.RESUMED
7849 || r.state == ActivityState.PAUSING
7850 || r.state == ActivityState.PAUSED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08007851 if (!r.isHomeActivity || mHomeProcess != r.app) {
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007852 Slog.w(TAG, " Force finishing activity "
7853 + r.intent.getComponent().flattenToShortString());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07007854 r.stack.finishActivityLocked(r, index,
Dianne Hackbornf83c5552010-03-31 22:19:32 -07007855 Activity.RESULT_CANCELED, null, "crashed");
7856 }
7857 }
7858 }
7859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007860 }
7861
7862 // Bump up the crash count of any services currently running in the proc.
7863 if (app.services.size() != 0) {
7864 // Any services running in the application need to be placed
7865 // back in the pending list.
Dianne Hackborn860755f2010-06-03 18:47:52 -07007866 Iterator<ServiceRecord> it = app.services.iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007867 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -07007868 ServiceRecord sr = it.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007869 sr.crashCount++;
7870 }
7871 }
Mattias Larssona4fd0072010-06-22 22:37:03 +02007872
7873 // If the crashing process is what we consider to be the "home process" and it has been
7874 // replaced by a third-party app, clear the package preferred activities from packages
7875 // with a home activity running in the process to prevent a repeatedly crashing app
7876 // from blocking the user to manually clear the list.
7877 if (app == mHomeProcess && mHomeProcess.activities.size() > 0
7878 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
7879 Iterator it = mHomeProcess.activities.iterator();
7880 while (it.hasNext()) {
Jean-Baptiste Queru5ea89f72010-07-30 09:30:31 -07007881 ActivityRecord r = (ActivityRecord)it.next();
Mattias Larssona4fd0072010-06-22 22:37:03 +02007882 if (r.isHomeActivity) {
7883 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
7884 try {
7885 ActivityThread.getPackageManager()
7886 .clearPackagePreferredActivities(r.packageName);
7887 } catch (RemoteException c) {
7888 // pm is in same process, this will never happen.
7889 }
7890 }
7891 }
7892 }
7893
Dianne Hackborna0c283e2012-02-09 10:47:01 -08007894 if (!app.isolated) {
7895 // XXX Can't keep track of crash times for isolated processes,
7896 // because they don't have a perisistent identity.
7897 mProcessCrashTimes.put(app.info.processName, app.uid, now);
7898 }
7899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007900 return true;
7901 }
7902
7903 void startAppProblemLocked(ProcessRecord app) {
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08007904 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
7905 mContext, app.info.packageName, app.info.flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 skipCurrentReceiverLocked(app);
7907 }
7908
7909 void skipCurrentReceiverLocked(ProcessRecord app) {
Christopher Tatef46723b2012-01-26 14:19:24 -08007910 for (BroadcastQueue queue : mBroadcastQueues) {
7911 queue.skipCurrentReceiverLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007912 }
7913 }
7914
Dan Egnor60d87622009-12-16 16:32:58 -08007915 /**
7916 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes.
7917 * The application process will exit immediately after this call returns.
7918 * @param app object of the crashing app, null for the system server
7919 * @param crashInfo describing the exception
7920 */
7921 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007922 ProcessRecord r = findAppProcess(app, "Crash");
Jeff Sharkeya353d262011-10-28 11:12:06 -07007923 final String processName = app == null ? "system_server"
7924 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08007925
7926 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07007927 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08007928 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08007929 crashInfo.exceptionClassName,
7930 crashInfo.exceptionMessage,
7931 crashInfo.throwFileName,
7932 crashInfo.throwLineNumber);
7933
Jeff Sharkeya353d262011-10-28 11:12:06 -07007934 addErrorToDropBox("crash", r, processName, null, null, null, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08007935
7936 crashApplication(r, crashInfo);
7937 }
7938
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007939 public void handleApplicationStrictModeViolation(
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007940 IBinder app,
7941 int violationMask,
7942 StrictMode.ViolationInfo info) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08007943 ProcessRecord r = findAppProcess(app, "StrictMode");
7944 if (r == null) {
7945 return;
7946 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007947
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007948 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) {
Brad Fitzpatrickf3d86be2010-11-23 10:31:52 -08007949 Integer stackFingerprint = info.hashCode();
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007950 boolean logIt = true;
7951 synchronized (mAlreadyLoggedViolatedStacks) {
7952 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) {
7953 logIt = false;
7954 // TODO: sub-sample into EventLog for these, with
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007955 // the info.durationMillis? Then we'd get
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007956 // the relative pain numbers, without logging all
7957 // the stack traces repeatedly. We'd want to do
7958 // likewise in the client code, which also does
7959 // dup suppression, before the Binder call.
7960 } else {
7961 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) {
7962 mAlreadyLoggedViolatedStacks.clear();
7963 }
7964 mAlreadyLoggedViolatedStacks.add(stackFingerprint);
7965 }
7966 }
7967 if (logIt) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007968 logStrictModeViolationToDropBox(r, info);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007969 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007970 }
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007971
7972 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) {
7973 AppErrorResult result = new AppErrorResult();
7974 synchronized (this) {
7975 final long origId = Binder.clearCallingIdentity();
7976
7977 Message msg = Message.obtain();
7978 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG;
7979 HashMap<String, Object> data = new HashMap<String, Object>();
7980 data.put("result", result);
7981 data.put("app", r);
Brad Fitzpatrick143666f2010-06-14 12:40:21 -07007982 data.put("violationMask", violationMask);
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007983 data.put("info", info);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007984 msg.obj = data;
7985 mHandler.sendMessage(msg);
7986
7987 Binder.restoreCallingIdentity(origId);
7988 }
7989 int res = result.get();
Dianne Hackbornb424b632010-08-18 15:59:05 -07007990 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res);
Brad Fitzpatrick46d42382010-06-11 13:57:58 -07007991 }
Brad Fitzpatrick438d0592010-06-10 12:19:19 -07007992 }
7993
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07007994 // Depending on the policy in effect, there could be a bunch of
7995 // these in quick succession so we try to batch these together to
7996 // minimize disk writes, number of dropbox entries, and maximize
7997 // compression, by having more fewer, larger records.
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07007998 private void logStrictModeViolationToDropBox(
7999 ProcessRecord process,
8000 StrictMode.ViolationInfo info) {
8001 if (info == null) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008002 return;
8003 }
8004 final boolean isSystemApp = process == null ||
8005 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM |
8006 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008007 final String processName = process == null ? "unknown" : process.processName;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008008 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode";
8009 final DropBoxManager dbox = (DropBoxManager)
8010 mContext.getSystemService(Context.DROPBOX_SERVICE);
8011
8012 // Exit early if the dropbox isn't configured to accept this report type.
8013 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8014
8015 boolean bufferWasEmpty;
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008016 boolean needsFlush;
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008017 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024);
8018 synchronized (sb) {
8019 bufferWasEmpty = sb.length() == 0;
Jeff Sharkeya353d262011-10-28 11:12:06 -07008020 appendDropBoxProcessHeaders(process, processName, sb);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008021 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
8022 sb.append("System-App: ").append(isSystemApp).append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008023 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n");
8024 if (info.violationNumThisLoop != 0) {
8025 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n");
8026 }
Brad Fitzpatrick599ca292010-10-22 14:47:03 -07008027 if (info.numAnimationsRunning != 0) {
8028 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n");
8029 }
Brad Fitzpatrickbfb19192010-10-29 15:25:44 -07008030 if (info.broadcastIntentAction != null) {
8031 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n");
8032 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008033 if (info.durationMillis != -1) {
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008034 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n");
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008035 }
Brad Fitzpatrickbfbe5772011-01-19 00:10:58 -08008036 if (info.numInstances != -1) {
8037 sb.append("Instance-Count: ").append(info.numInstances).append("\n");
8038 }
Brad Fitzpatricke7520d82010-11-10 18:08:36 -08008039 if (info.tags != null) {
8040 for (String tag : info.tags) {
8041 sb.append("Span-Tag: ").append(tag).append("\n");
8042 }
8043 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008044 sb.append("\n");
Brad Fitzpatrickcb9ceb12010-07-29 14:29:02 -07008045 if (info.crashInfo != null && info.crashInfo.stackTrace != null) {
8046 sb.append(info.crashInfo.stackTrace);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008047 }
8048 sb.append("\n");
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008049
8050 // Only buffer up to ~64k. Various logging bits truncate
8051 // things at 128k.
8052 needsFlush = (sb.length() > 64 * 1024);
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008053 }
8054
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008055 // Flush immediately if the buffer's grown too large, or this
8056 // is a non-system app. Non-system apps are isolated with a
8057 // different tag & policy and not batched.
8058 //
8059 // Batching is useful during internal testing with
8060 // StrictMode settings turned up high. Without batching,
8061 // thousands of separate files could be created on boot.
8062 if (!isSystemApp || needsFlush) {
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008063 new Thread("Error dump: " + dropboxTag) {
8064 @Override
8065 public void run() {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008066 String report;
8067 synchronized (sb) {
8068 report = sb.toString();
8069 sb.delete(0, sb.length());
8070 sb.trimToSize();
8071 }
8072 if (report.length() != 0) {
8073 dbox.addText(dropboxTag, report);
8074 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008075 }
8076 }.start();
8077 return;
8078 }
8079
8080 // System app batching:
8081 if (!bufferWasEmpty) {
Brad Fitzpatricke73eb532010-07-27 16:54:39 -07008082 // An existing dropbox-writing thread is outstanding, so
8083 // we don't need to start it up. The existing thread will
8084 // catch the buffer appends we just did.
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008085 return;
8086 }
8087
8088 // Worker thread to both batch writes and to avoid blocking the caller on I/O.
8089 // (After this point, we shouldn't access AMS internal data structures.)
8090 new Thread("Error dump: " + dropboxTag) {
8091 @Override
8092 public void run() {
8093 // 5 second sleep to let stacks arrive and be batched together
8094 try {
8095 Thread.sleep(5000); // 5 seconds
8096 } catch (InterruptedException e) {}
8097
8098 String errorReport;
8099 synchronized (mStrictModeBuffer) {
8100 errorReport = mStrictModeBuffer.toString();
8101 if (errorReport.length() == 0) {
8102 return;
8103 }
8104 mStrictModeBuffer.delete(0, mStrictModeBuffer.length());
8105 mStrictModeBuffer.trimToSize();
8106 }
8107 dbox.addText(dropboxTag, errorReport);
8108 }
8109 }.start();
8110 }
8111
Dan Egnor60d87622009-12-16 16:32:58 -08008112 /**
8113 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors.
8114 * @param app object of the crashing app, null for the system server
8115 * @param tag reported by the caller
8116 * @param crashInfo describing the context of the error
8117 * @return true if the process should exit immediately (WTF is fatal)
8118 */
8119 public boolean handleApplicationWtf(IBinder app, String tag,
Dan Egnorb7f03672009-12-09 16:22:32 -08008120 ApplicationErrorReport.CrashInfo crashInfo) {
Dianne Hackborncb44d962011-03-10 17:02:27 -08008121 ProcessRecord r = findAppProcess(app, "WTF");
Jeff Sharkeya353d262011-10-28 11:12:06 -07008122 final String processName = app == null ? "system_server"
8123 : (r == null ? "unknown" : r.processName);
Dan Egnor60d87622009-12-16 16:32:58 -08008124
8125 EventLog.writeEvent(EventLogTags.AM_WTF, Binder.getCallingPid(),
Jeff Sharkeya353d262011-10-28 11:12:06 -07008126 processName,
Dan Egnor2780e732010-01-22 14:47:35 -08008127 r == null ? -1 : r.info.flags,
Dan Egnor60d87622009-12-16 16:32:58 -08008128 tag, crashInfo.exceptionMessage);
8129
Jeff Sharkeya353d262011-10-28 11:12:06 -07008130 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo);
Dan Egnor60d87622009-12-16 16:32:58 -08008131
Dianne Hackborn1ab43772011-03-15 14:38:02 -07008132 if (r != null && r.pid != Process.myPid() &&
8133 Settings.Secure.getInt(mContext.getContentResolver(),
8134 Settings.Secure.WTF_IS_FATAL, 0) != 0) {
Dan Egnor60d87622009-12-16 16:32:58 -08008135 crashApplication(r, crashInfo);
8136 return true;
8137 } else {
8138 return false;
8139 }
8140 }
8141
8142 /**
8143 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit})
8144 * @return the corresponding {@link ProcessRecord} object, or null if none could be found
8145 */
Dianne Hackborncb44d962011-03-10 17:02:27 -08008146 private ProcessRecord findAppProcess(IBinder app, String reason) {
Dan Egnor60d87622009-12-16 16:32:58 -08008147 if (app == null) {
8148 return null;
8149 }
8150
8151 synchronized (this) {
8152 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) {
8153 final int NA = apps.size();
8154 for (int ia=0; ia<NA; ia++) {
8155 ProcessRecord p = apps.valueAt(ia);
8156 if (p.thread != null && p.thread.asBinder() == app) {
8157 return p;
8158 }
8159 }
8160 }
8161
Dianne Hackborncb44d962011-03-10 17:02:27 -08008162 Slog.w(TAG, "Can't find mystery application for " + reason
8163 + " from pid=" + Binder.getCallingPid()
8164 + " uid=" + Binder.getCallingUid() + ": " + app);
Dan Egnor60d87622009-12-16 16:32:58 -08008165 return null;
8166 }
8167 }
8168
8169 /**
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008170 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging
8171 * to append various headers to the dropbox log text.
Dan Egnor60d87622009-12-16 16:32:58 -08008172 */
Jeff Sharkeya353d262011-10-28 11:12:06 -07008173 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName,
8174 StringBuilder sb) {
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008175 // Watchdog thread ends up invoking this function (with
8176 // a null ProcessRecord) to add the stack file to dropbox.
8177 // Do not acquire a lock on this (am) in such cases, as it
8178 // could cause a potential deadlock, if and when watchdog
8179 // is invoked due to unavailability of lock on am and it
8180 // would prevent watchdog from killing system_server.
8181 if (process == null) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008182 sb.append("Process: ").append(processName).append("\n");
Vairavan Srinivasan68a4e0a2011-02-14 20:45:59 -08008183 return;
8184 }
Brad Fitzpatrick1e02d362010-09-10 09:19:50 -07008185 // Note: ProcessRecord 'process' is guarded by the service
8186 // instance. (notably process.pkgList, which could otherwise change
8187 // concurrently during execution of this method)
8188 synchronized (this) {
Jeff Sharkeya353d262011-10-28 11:12:06 -07008189 sb.append("Process: ").append(processName).append("\n");
Dan Egnora455d192010-03-12 08:52:28 -08008190 int flags = process.info.flags;
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008191 IPackageManager pm = AppGlobals.getPackageManager();
Dan Egnora455d192010-03-12 08:52:28 -08008192 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n");
8193 for (String pkg : process.pkgList) {
8194 sb.append("Package: ").append(pkg);
Dan Egnor42471dd2010-01-07 17:25:22 -08008195 try {
Amith Yamasanif203aee2012-08-29 18:41:53 -07008196 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId());
Dan Egnora455d192010-03-12 08:52:28 -08008197 if (pi != null) {
8198 sb.append(" v").append(pi.versionCode);
8199 if (pi.versionName != null) {
8200 sb.append(" (").append(pi.versionName).append(")");
8201 }
8202 }
8203 } catch (RemoteException e) {
8204 Slog.e(TAG, "Error getting package info: " + pkg, e);
Dan Egnor60d87622009-12-16 16:32:58 -08008205 }
Dan Egnora455d192010-03-12 08:52:28 -08008206 sb.append("\n");
Dan Egnor60d87622009-12-16 16:32:58 -08008207 }
Dan Egnora455d192010-03-12 08:52:28 -08008208 }
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008209 }
8210
8211 private static String processClass(ProcessRecord process) {
8212 if (process == null || process.pid == MY_PID) {
8213 return "system_server";
8214 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8215 return "system_app";
8216 } else {
8217 return "data_app";
8218 }
8219 }
8220
8221 /**
8222 * Write a description of an error (crash, WTF, ANR) to the drop box.
8223 * @param eventType to include in the drop box tag ("crash", "wtf", etc.)
8224 * @param process which caused the error, null means the system server
8225 * @param activity which triggered the error, null if unknown
8226 * @param parent activity related to the error, null if unknown
8227 * @param subject line related to the error, null if absent
8228 * @param report in long form describing the error, null if absent
8229 * @param logFile to include in the report, null if none
8230 * @param crashInfo giving an application stack trace, null if absent
8231 */
8232 public void addErrorToDropBox(String eventType,
Jeff Sharkeya353d262011-10-28 11:12:06 -07008233 ProcessRecord process, String processName, ActivityRecord activity,
8234 ActivityRecord parent, String subject,
Brad Fitzpatrickad13b982010-07-14 12:35:53 -07008235 final String report, final File logFile,
8236 final ApplicationErrorReport.CrashInfo crashInfo) {
8237 // NOTE -- this must never acquire the ActivityManagerService lock,
8238 // otherwise the watchdog may be prevented from resetting the system.
8239
8240 final String dropboxTag = processClass(process) + "_" + eventType;
8241 final DropBoxManager dbox = (DropBoxManager)
8242 mContext.getSystemService(Context.DROPBOX_SERVICE);
8243
8244 // Exit early if the dropbox isn't configured to accept this report type.
8245 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return;
8246
8247 final StringBuilder sb = new StringBuilder(1024);
Jeff Sharkeya353d262011-10-28 11:12:06 -07008248 appendDropBoxProcessHeaders(process, processName, sb);
Dan Egnora455d192010-03-12 08:52:28 -08008249 if (activity != null) {
8250 sb.append("Activity: ").append(activity.shortComponentName).append("\n");
8251 }
8252 if (parent != null && parent.app != null && parent.app.pid != process.pid) {
8253 sb.append("Parent-Process: ").append(parent.app.processName).append("\n");
8254 }
8255 if (parent != null && parent != activity) {
8256 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n");
8257 }
8258 if (subject != null) {
8259 sb.append("Subject: ").append(subject).append("\n");
8260 }
8261 sb.append("Build: ").append(Build.FINGERPRINT).append("\n");
Christian Lindeberg03d2ca62010-09-28 14:52:20 +02008262 if (Debug.isDebuggerConnected()) {
8263 sb.append("Debugger: Connected\n");
8264 }
Dan Egnora455d192010-03-12 08:52:28 -08008265 sb.append("\n");
8266
8267 // Do the rest in a worker thread to avoid blocking the caller on I/O
8268 // (After this point, we shouldn't access AMS internal data structures.)
8269 Thread worker = new Thread("Error dump: " + dropboxTag) {
8270 @Override
8271 public void run() {
8272 if (report != null) {
8273 sb.append(report);
8274 }
8275 if (logFile != null) {
8276 try {
8277 sb.append(FileUtils.readTextFile(logFile, 128 * 1024, "\n\n[[TRUNCATED]]"));
8278 } catch (IOException e) {
8279 Slog.e(TAG, "Error reading " + logFile, e);
8280 }
8281 }
8282 if (crashInfo != null && crashInfo.stackTrace != null) {
8283 sb.append(crashInfo.stackTrace);
8284 }
8285
8286 String setting = Settings.Secure.ERROR_LOGCAT_PREFIX + dropboxTag;
8287 int lines = Settings.Secure.getInt(mContext.getContentResolver(), setting, 0);
8288 if (lines > 0) {
8289 sb.append("\n");
8290
8291 // Merge several logcat streams, and take the last N lines
8292 InputStreamReader input = null;
8293 try {
8294 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat",
8295 "-v", "time", "-b", "events", "-b", "system", "-b", "main",
8296 "-t", String.valueOf(lines)).redirectErrorStream(true).start();
8297
8298 try { logcat.getOutputStream().close(); } catch (IOException e) {}
8299 try { logcat.getErrorStream().close(); } catch (IOException e) {}
8300 input = new InputStreamReader(logcat.getInputStream());
8301
8302 int num;
8303 char[] buf = new char[8192];
8304 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num);
8305 } catch (IOException e) {
8306 Slog.e(TAG, "Error running logcat", e);
8307 } finally {
8308 if (input != null) try { input.close(); } catch (IOException e) {}
8309 }
8310 }
8311
8312 dbox.addText(dropboxTag, sb.toString());
Dan Egnor60d87622009-12-16 16:32:58 -08008313 }
Dan Egnora455d192010-03-12 08:52:28 -08008314 };
8315
Dianne Hackborn56385cc2012-04-30 15:07:47 -07008316 if (process == null) {
8317 // If process is null, we are being called from some internal code
8318 // and may be about to die -- run this synchronously.
8319 worker.run();
Dan Egnora455d192010-03-12 08:52:28 -08008320 } else {
8321 worker.start();
Dan Egnor60d87622009-12-16 16:32:58 -08008322 }
8323 }
8324
8325 /**
8326 * Bring up the "unexpected error" dialog box for a crashing app.
8327 * Deal with edge cases (intercepts from instrumented applications,
8328 * ActivityController, error intent receivers, that sort of thing).
8329 * @param r the application crashing
8330 * @param crashInfo describing the failure
8331 */
8332 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008333 long timeMillis = System.currentTimeMillis();
8334 String shortMsg = crashInfo.exceptionClassName;
8335 String longMsg = crashInfo.exceptionMessage;
8336 String stackTrace = crashInfo.stackTrace;
8337 if (shortMsg != null && longMsg != null) {
8338 longMsg = shortMsg + ": " + longMsg;
8339 } else if (shortMsg != null) {
8340 longMsg = shortMsg;
8341 }
8342
Dan Egnor60d87622009-12-16 16:32:58 -08008343 AppErrorResult result = new AppErrorResult();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008344 synchronized (this) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008345 if (mController != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008346 try {
8347 String name = r != null ? r.processName : null;
8348 int pid = r != null ? r.pid : Binder.getCallingPid();
Dan Egnor60d87622009-12-16 16:32:58 -08008349 if (!mController.appCrashed(name, pid,
Dan Egnorb7f03672009-12-09 16:22:32 -08008350 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008351 Slog.w(TAG, "Force-killing crashed app " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 + " at watcher's request");
8353 Process.killProcess(pid);
Dan Egnorb7f03672009-12-09 16:22:32 -08008354 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008355 }
8356 } catch (RemoteException e) {
Dianne Hackbornb06ea702009-07-13 13:07:51 -07008357 mController = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008358 }
8359 }
8360
8361 final long origId = Binder.clearCallingIdentity();
8362
8363 // If this process is running instrumentation, finish it.
8364 if (r != null && r.instrumentationClass != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008365 Slog.w(TAG, "Error in app " + r.processName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008366 + " running instrumentation " + r.instrumentationClass + ":");
Joe Onorato8a9b2202010-02-26 18:56:32 -08008367 if (shortMsg != null) Slog.w(TAG, " " + shortMsg);
8368 if (longMsg != null) Slog.w(TAG, " " + longMsg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008369 Bundle info = new Bundle();
8370 info.putString("shortMsg", shortMsg);
8371 info.putString("longMsg", longMsg);
8372 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info);
8373 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008374 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008375 }
8376
Dan Egnor60d87622009-12-16 16:32:58 -08008377 // If we can't identify the process or it's already exceeded its crash quota,
8378 // quit right away without showing a crash dialog.
8379 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008380 Binder.restoreCallingIdentity(origId);
Dan Egnorb7f03672009-12-09 16:22:32 -08008381 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008382 }
8383
8384 Message msg = Message.obtain();
8385 msg.what = SHOW_ERROR_MSG;
8386 HashMap data = new HashMap();
8387 data.put("result", result);
8388 data.put("app", r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008389 msg.obj = data;
8390 mHandler.sendMessage(msg);
8391
8392 Binder.restoreCallingIdentity(origId);
8393 }
8394
8395 int res = result.get();
8396
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008397 Intent appErrorIntent = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008398 synchronized (this) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008399 if (r != null && !r.isolated) {
8400 // XXX Can't keep track of crash time for isolated processes,
8401 // since they don't have a persistent identity.
8402 mProcessCrashTimes.put(r.info.processName, r.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008403 SystemClock.uptimeMillis());
8404 }
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008405 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
Dan Egnorb7f03672009-12-09 16:22:32 -08008406 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008407 }
8408 }
8409
8410 if (appErrorIntent != null) {
8411 try {
8412 mContext.startActivity(appErrorIntent);
8413 } catch (ActivityNotFoundException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008414 Slog.w(TAG, "bug report receiver dissappeared", e);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008415 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008417 }
Dan Egnorb7f03672009-12-09 16:22:32 -08008418
8419 Intent createAppErrorIntentLocked(ProcessRecord r,
8420 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
8421 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008422 if (report == null) {
8423 return null;
8424 }
8425 Intent result = new Intent(Intent.ACTION_APP_ERROR);
8426 result.setComponent(r.errorReportReceiver);
8427 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
8428 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
8429 return result;
8430 }
8431
Dan Egnorb7f03672009-12-09 16:22:32 -08008432 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
8433 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008434 if (r.errorReportReceiver == null) {
8435 return null;
8436 }
8437
8438 if (!r.crashing && !r.notResponding) {
8439 return null;
8440 }
8441
Dan Egnorb7f03672009-12-09 16:22:32 -08008442 ApplicationErrorReport report = new ApplicationErrorReport();
8443 report.packageName = r.info.packageName;
8444 report.installerPackageName = r.errorReportReceiver.getPackageName();
8445 report.processName = r.processName;
8446 report.time = timeMillis;
Jacek Surazskie0ee6ef2010-01-07 16:23:03 +01008447 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008448
Dan Egnorb7f03672009-12-09 16:22:32 -08008449 if (r.crashing) {
8450 report.type = ApplicationErrorReport.TYPE_CRASH;
8451 report.crashInfo = crashInfo;
8452 } else if (r.notResponding) {
8453 report.type = ApplicationErrorReport.TYPE_ANR;
8454 report.anrInfo = new ApplicationErrorReport.AnrInfo();
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008455
Dan Egnorb7f03672009-12-09 16:22:32 -08008456 report.anrInfo.activity = r.notRespondingReport.tag;
8457 report.anrInfo.cause = r.notRespondingReport.shortMsg;
8458 report.anrInfo.info = r.notRespondingReport.longMsg;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008459 }
8460
Dan Egnorb7f03672009-12-09 16:22:32 -08008461 return report;
Jacek Surazskif5b9c722009-05-18 12:09:59 +02008462 }
8463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008464 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008465 enforceNotIsolatedCaller("getProcessesInErrorState");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008466 // assume our apps are happy - lazy create the list
8467 List<ActivityManager.ProcessErrorStateInfo> errList = null;
8468
Dianne Hackborn0c380492012-08-20 17:23:30 -07008469 final boolean allUsers = ActivityManager.checkUidPermission(
8470 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8471 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8472 int userId = UserHandle.getUserId(Binder.getCallingUid());
8473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008474 synchronized (this) {
8475
8476 // iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008477 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8478 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008479 if (!allUsers && app.userId != userId) {
8480 continue;
8481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008482 if ((app.thread != null) && (app.crashing || app.notResponding)) {
8483 // This one's in trouble, so we'll generate a report for it
8484 // crashes are higher priority (in case there's a crash *and* an anr)
8485 ActivityManager.ProcessErrorStateInfo report = null;
8486 if (app.crashing) {
8487 report = app.crashingReport;
8488 } else if (app.notResponding) {
8489 report = app.notRespondingReport;
8490 }
8491
8492 if (report != null) {
8493 if (errList == null) {
8494 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1);
8495 }
8496 errList.add(report);
8497 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08008498 Slog.w(TAG, "Missing app error report, app = " + app.processName +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008499 " crashing = " + app.crashing +
8500 " notResponding = " + app.notResponding);
8501 }
8502 }
8503 }
8504 }
8505
8506 return errList;
8507 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07008508
8509 static int oomAdjToImportance(int adj, ActivityManager.RunningAppProcessInfo currApp) {
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008510 if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008511 if (currApp != null) {
8512 currApp.lru = adj - ProcessList.HIDDEN_APP_MIN_ADJ + 1;
8513 }
8514 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008515 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
8516 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008517 } else if (adj >= ProcessList.HOME_APP_ADJ) {
8518 if (currApp != null) {
8519 currApp.lru = 0;
8520 }
8521 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07008522 } else if (adj >= ProcessList.SERVICE_ADJ) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07008523 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
8524 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
8525 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
8526 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
8527 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
8528 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
8529 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
8530 } else {
8531 return ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
8532 }
8533 }
8534
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008535 private void fillInProcMemInfo(ProcessRecord app,
8536 ActivityManager.RunningAppProcessInfo outInfo) {
8537 outInfo.pid = app.pid;
8538 outInfo.uid = app.info.uid;
8539 if (mHeavyWeightProcess == app) {
8540 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE;
8541 }
8542 if (app.persistent) {
8543 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT;
8544 }
Dianne Hackborn0c380492012-08-20 17:23:30 -07008545 if (app.hasActivities) {
8546 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES;
8547 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008548 outInfo.lastTrimLevel = app.trimMemoryLevel;
8549 int adj = app.curAdj;
8550 outInfo.importance = oomAdjToImportance(adj, outInfo);
8551 outInfo.importanceReasonCode = app.adjTypeCode;
8552 }
8553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008555 enforceNotIsolatedCaller("getRunningAppProcesses");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556 // Lazy instantiation of list
8557 List<ActivityManager.RunningAppProcessInfo> runList = null;
Dianne Hackborn0c380492012-08-20 17:23:30 -07008558 final boolean allUsers = ActivityManager.checkUidPermission(
8559 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
8560 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED;
8561 int userId = UserHandle.getUserId(Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008562 synchronized (this) {
8563 // Iterate across all processes
Dianne Hackborndd71fc82009-12-16 19:24:32 -08008564 for (int i=mLruProcesses.size()-1; i>=0; i--) {
8565 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn0c380492012-08-20 17:23:30 -07008566 if (!allUsers && app.userId != userId) {
8567 continue;
8568 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008569 if ((app.thread != null) && (!app.crashing && !app.notResponding)) {
8570 // Generate process state info for running application
8571 ActivityManager.RunningAppProcessInfo currApp =
8572 new ActivityManager.RunningAppProcessInfo(app.processName,
8573 app.pid, app.getPackageList());
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008574 fillInProcMemInfo(app, currApp);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008575 if (app.adjSource instanceof ProcessRecord) {
8576 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008577 currApp.importanceReasonImportance = oomAdjToImportance(
8578 app.adjSourceOom, null);
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008579 } else if (app.adjSource instanceof ActivityRecord) {
8580 ActivityRecord r = (ActivityRecord)app.adjSource;
Dianne Hackborndd9b82c2009-09-03 00:18:47 -07008581 if (r.app != null) currApp.importanceReasonPid = r.app.pid;
8582 }
8583 if (app.adjTarget instanceof ComponentName) {
8584 currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
8585 }
Joe Onorato8a9b2202010-02-26 18:56:32 -08008586 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008587 // + " lru=" + currApp.lru);
8588 if (runList == null) {
8589 runList = new ArrayList<ActivityManager.RunningAppProcessInfo>();
8590 }
8591 runList.add(currApp);
8592 }
8593 }
8594 }
8595 return runList;
8596 }
8597
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008598 public List<ApplicationInfo> getRunningExternalApplications() {
Dianne Hackborna573f6a2012-02-09 16:12:18 -08008599 enforceNotIsolatedCaller("getRunningExternalApplications");
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008600 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses();
8601 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>();
8602 if (runningApps != null && runningApps.size() > 0) {
8603 Set<String> extList = new HashSet<String>();
8604 for (ActivityManager.RunningAppProcessInfo app : runningApps) {
8605 if (app.pkgList != null) {
8606 for (String pkg : app.pkgList) {
8607 extList.add(pkg);
8608 }
8609 }
8610 }
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -07008611 IPackageManager pm = AppGlobals.getPackageManager();
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008612 for (String pkg : extList) {
8613 try {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07008614 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId());
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07008615 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
8616 retList.add(info);
8617 }
8618 } catch (RemoteException e) {
8619 }
8620 }
8621 }
8622 return retList;
8623 }
8624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625 @Override
Dianne Hackborn27ff9132012-03-06 14:57:58 -08008626 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) {
8627 enforceNotIsolatedCaller("getMyMemoryState");
8628 synchronized (this) {
8629 ProcessRecord proc;
8630 synchronized (mPidsSelfLocked) {
8631 proc = mPidsSelfLocked.get(Binder.getCallingPid());
8632 }
8633 fillInProcMemInfo(proc, outInfo);
8634 }
8635 }
8636
8637 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008638 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008639 if (checkCallingPermission(android.Manifest.permission.DUMP)
8640 != PackageManager.PERMISSION_GRANTED) {
8641 pw.println("Permission Denial: can't dump ActivityManager from from pid="
8642 + Binder.getCallingPid()
8643 + ", uid=" + Binder.getCallingUid()
8644 + " without permission "
8645 + android.Manifest.permission.DUMP);
8646 return;
8647 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008648
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008649 boolean dumpAll = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008650 boolean dumpClient = false;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008651 String dumpPackage = null;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008652
8653 int opti = 0;
8654 while (opti < args.length) {
8655 String opt = args[opti];
8656 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
8657 break;
8658 }
8659 opti++;
8660 if ("-a".equals(opt)) {
8661 dumpAll = true;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008662 } else if ("-c".equals(opt)) {
8663 dumpClient = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008664 } else if ("-h".equals(opt)) {
8665 pw.println("Activity manager dump options:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008666 pw.println(" [-a] [-c] [-h] [cmd] ...");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008667 pw.println(" cmd may be one of:");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008668 pw.println(" a[ctivities]: activity stack state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008669 pw.println(" b[roadcasts] [PACKAGE_NAME]: broadcast state");
8670 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state");
8671 pw.println(" p[rocesses] [PACKAGE_NAME]: process state");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008672 pw.println(" o[om]: out of memory management");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008673 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state");
Marco Nelissen18cb2872011-11-15 11:19:53 -08008674 pw.println(" provider [COMP_SPEC]: provider client-side state");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008675 pw.println(" s[ervices] [COMP_SPEC ...]: service state");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008676 pw.println(" service [COMP_SPEC]: service client-side state");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008677 pw.println(" package [PACKAGE_NAME]: all state related to given package");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008678 pw.println(" all: dump all activities");
8679 pw.println(" top: dump the top activity");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008680 pw.println(" cmd may also be a COMP_SPEC to dump activities.");
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07008681 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),");
8682 pw.println(" a partial substring in a component name, a");
8683 pw.println(" hex object identifier.");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008684 pw.println(" -a: include all available server state.");
8685 pw.println(" -c: include client state.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 return;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008687 } else {
8688 pw.println("Unknown argument: " + opt + "; use -h for help");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008689 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008690 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008691
8692 long origId = Binder.clearCallingIdentity();
8693 boolean more = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008694 // Is the caller requesting to dump a particular piece of data?
8695 if (opti < args.length) {
8696 String cmd = args[opti];
8697 opti++;
8698 if ("activities".equals(cmd) || "a".equals(cmd)) {
8699 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008700 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008701 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008702 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008703 String[] newArgs;
8704 String name;
8705 if (opti >= args.length) {
8706 name = null;
8707 newArgs = EMPTY_STRING_ARRAY;
8708 } else {
8709 name = args[opti];
8710 opti++;
8711 newArgs = new String[args.length - opti];
8712 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8713 args.length - opti);
8714 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008715 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008716 dumpBroadcastsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008717 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008718 } else if ("intents".equals(cmd) || "i".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008719 String[] newArgs;
8720 String name;
8721 if (opti >= args.length) {
8722 name = null;
8723 newArgs = EMPTY_STRING_ARRAY;
8724 } else {
8725 name = args[opti];
8726 opti++;
8727 newArgs = new String[args.length - opti];
8728 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8729 args.length - opti);
8730 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008731 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008732 dumpPendingIntentsLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008733 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008734 } else if ("processes".equals(cmd) || "p".equals(cmd)) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008735 String[] newArgs;
8736 String name;
8737 if (opti >= args.length) {
8738 name = null;
8739 newArgs = EMPTY_STRING_ARRAY;
8740 } else {
8741 name = args[opti];
8742 opti++;
8743 newArgs = new String[args.length - opti];
8744 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8745 args.length - opti);
8746 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008747 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008748 dumpProcessesLocked(fd, pw, args, opti, true, name);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008749 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008750 } else if ("oom".equals(cmd) || "o".equals(cmd)) {
8751 synchronized (this) {
8752 dumpOomLocked(fd, pw, args, opti, true);
8753 }
Marco Nelissen18cb2872011-11-15 11:19:53 -08008754 } else if ("provider".equals(cmd)) {
8755 String[] newArgs;
8756 String name;
8757 if (opti >= args.length) {
8758 name = null;
8759 newArgs = EMPTY_STRING_ARRAY;
8760 } else {
8761 name = args[opti];
8762 opti++;
8763 newArgs = new String[args.length - opti];
8764 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
8765 }
8766 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) {
8767 pw.println("No providers match: " + name);
8768 pw.println("Use -h for help.");
8769 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008770 } else if ("providers".equals(cmd) || "prov".equals(cmd)) {
8771 synchronized (this) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008772 dumpProvidersLocked(fd, pw, args, opti, true, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008773 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008774 } else if ("service".equals(cmd)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008775 String[] newArgs;
8776 String name;
8777 if (opti >= args.length) {
8778 name = null;
8779 newArgs = EMPTY_STRING_ARRAY;
8780 } else {
8781 name = args[opti];
8782 opti++;
8783 newArgs = new String[args.length - opti];
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008784 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8785 args.length - opti);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008786 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008787 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008788 pw.println("No services match: " + name);
8789 pw.println("Use -h for help.");
8790 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008791 } else if ("package".equals(cmd)) {
8792 String[] newArgs;
8793 if (opti >= args.length) {
8794 pw.println("package: no package name specified");
8795 pw.println("Use -h for help.");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008796 } else {
8797 dumpPackage = args[opti];
8798 opti++;
8799 newArgs = new String[args.length - opti];
8800 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0,
8801 args.length - opti);
8802 args = newArgs;
8803 opti = 0;
Amith Yamasani7463ada2012-04-11 15:02:39 -07008804 more = true;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008805 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008806 } else if ("services".equals(cmd) || "s".equals(cmd)) {
8807 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008808 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, null);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008809 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07008810 } else {
8811 // Dumping a single activity?
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008812 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) {
8813 pw.println("Bad activity command, or no activities match: " + cmd);
8814 pw.println("Use -h for help.");
Dianne Hackborn625ac272010-09-17 18:29:22 -07008815 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008816 }
8817 if (!more) {
8818 Binder.restoreCallingIdentity(origId);
Dianne Hackborn30d71892010-12-11 10:37:55 -08008819 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008820 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008821 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008822
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008823 // No piece of data specified, dump everything.
8824 synchronized (this) {
8825 boolean needSep;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008826 needSep = dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008827 if (needSep) {
8828 pw.println(" ");
8829 }
8830 if (dumpAll) {
8831 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008832 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008833 needSep = dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008834 if (needSep) {
8835 pw.println(" ");
8836 }
8837 if (dumpAll) {
8838 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008839 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008840 needSep = dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008841 if (needSep) {
8842 pw.println(" ");
8843 }
8844 if (dumpAll) {
8845 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008846 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -07008847 needSep = mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008848 if (needSep) {
8849 pw.println(" ");
8850 }
8851 if (dumpAll) {
8852 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008853 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008854 needSep = dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008855 if (needSep) {
8856 pw.println(" ");
8857 }
8858 if (dumpAll) {
8859 pw.println("-------------------------------------------------------------------------------");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008860 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008861 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008862 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008863 Binder.restoreCallingIdentity(origId);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008864 }
Amith Yamasani7463ada2012-04-11 15:02:39 -07008865
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008866 boolean dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008867 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008868 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)");
8869 pw.println(" Main stack:");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008870 dumpHistoryList(fd, pw, mMainStack.mHistory, " ", "Hist", true, !dumpAll, dumpClient,
8871 dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008872 pw.println(" ");
8873 pw.println(" Running activities (most recent first):");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008874 dumpHistoryList(fd, pw, mMainStack.mLRUActivities, " ", "Run", false, !dumpAll, false,
8875 dumpPackage);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008876 if (mMainStack.mWaitingVisibleActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008877 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008878 pw.println(" Activities waiting for another to become visible:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008879 dumpHistoryList(fd, pw, mMainStack.mWaitingVisibleActivities, " ", "Wait", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008880 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008881 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008882 if (mMainStack.mStoppingActivities.size() > 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 pw.println(" ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008884 pw.println(" Activities waiting to stop:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008885 dumpHistoryList(fd, pw, mMainStack.mStoppingActivities, " ", "Stop", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008886 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008887 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008888 if (mMainStack.mGoingToSleepActivities.size() > 0) {
8889 pw.println(" ");
8890 pw.println(" Activities waiting to sleep:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008891 dumpHistoryList(fd, pw, mMainStack.mGoingToSleepActivities, " ", "Sleep", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008892 !dumpAll, false, dumpPackage);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08008893 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008894 if (mMainStack.mFinishingActivities.size() > 0) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008895 pw.println(" ");
8896 pw.println(" Activities waiting to finish:");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008897 dumpHistoryList(fd, pw, mMainStack.mFinishingActivities, " ", "Fin", false,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008898 !dumpAll, false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008900
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008901 pw.println(" ");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08008902 if (mMainStack.mPausingActivity != null) {
8903 pw.println(" mPausingActivity: " + mMainStack.mPausingActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008904 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07008905 pw.println(" mResumedActivity: " + mMainStack.mResumedActivity);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008906 pw.println(" mFocusedActivity: " + mFocusedActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008907 if (dumpAll) {
8908 pw.println(" mLastPausedActivity: " + mMainStack.mLastPausedActivity);
8909 pw.println(" mSleepTimeout: " + mMainStack.mSleepTimeout);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07008910 pw.println(" mDismissKeyguardOnNextActivity: "
8911 + mMainStack.mDismissKeyguardOnNextActivity);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008913
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008914 if (mRecentTasks.size() > 0) {
8915 pw.println();
8916 pw.println(" Recent tasks:");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008917
8918 final int N = mRecentTasks.size();
8919 for (int i=0; i<N; i++) {
8920 TaskRecord tr = mRecentTasks.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008921 if (dumpPackage != null) {
8922 if (tr.realActivity == null ||
8923 !dumpPackage.equals(tr.realActivity)) {
8924 continue;
8925 }
8926 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008927 pw.print(" * Recent #"); pw.print(i); pw.print(": ");
8928 pw.println(tr);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008929 if (dumpAll) {
8930 mRecentTasks.get(i).dump(pw, " ");
8931 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008932 }
8933 }
8934
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008935 if (dumpAll) {
8936 pw.println(" ");
8937 pw.println(" mCurTask: " + mCurTask);
8938 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008939
8940 return true;
8941 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07008942
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008943 boolean dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008944 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008945 boolean needSep = false;
8946 int numPers = 0;
8947
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008948 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)");
8949
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008950 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008951 for (SparseArray<ProcessRecord> procs : mProcessNames.getMap().values()) {
8952 final int NA = procs.size();
8953 for (int ia=0; ia<NA; ia++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008954 ProcessRecord r = procs.valueAt(ia);
8955 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8956 continue;
8957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008958 if (!needSep) {
8959 pw.println(" All known processes:");
8960 needSep = true;
8961 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008962 pw.print(r.persistent ? " *PERS*" : " *APP*");
8963 pw.print(" UID "); pw.print(procs.keyAt(ia));
8964 pw.print(" "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 r.dump(pw, " ");
8966 if (r.persistent) {
8967 numPers++;
8968 }
8969 }
8970 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008971 }
Dianne Hackborna0c283e2012-02-09 10:47:01 -08008972
8973 if (mIsolatedProcesses.size() > 0) {
8974 if (needSep) pw.println(" ");
8975 needSep = true;
8976 pw.println(" Isolated process list (sorted by uid):");
8977 for (int i=0; i<mIsolatedProcesses.size(); i++) {
8978 ProcessRecord r = mIsolatedProcesses.valueAt(i);
8979 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
8980 continue;
8981 }
8982 pw.println(String.format("%sIsolated #%2d: %s",
8983 " ", i, r.toString()));
8984 }
8985 }
8986
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008987 if (mLruProcesses.size() > 0) {
8988 if (needSep) pw.println(" ");
8989 needSep = true;
Dianne Hackborn905577f2011-09-07 18:31:28 -07008990 pw.println(" Process LRU list (sorted by oom_adj):");
Dianne Hackborn287952c2010-09-22 22:34:31 -07008991 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008992 "Proc", "PERS", false, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08008993 needSep = true;
8994 }
8995
Dianne Hackborne17aeb32011-04-07 15:11:57 -07008996 if (dumpAll) {
8997 synchronized (mPidsSelfLocked) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08008998 boolean printed = false;
8999 for (int i=0; i<mPidsSelfLocked.size(); i++) {
9000 ProcessRecord r = mPidsSelfLocked.valueAt(i);
9001 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9002 continue;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009003 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009004 if (!printed) {
9005 if (needSep) pw.println(" ");
9006 needSep = true;
9007 pw.println(" PID mappings:");
9008 printed = true;
9009 }
9010 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i));
9011 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009012 }
9013 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009014 }
9015
9016 if (mForegroundProcesses.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009017 synchronized (mPidsSelfLocked) {
9018 boolean printed = false;
9019 for (int i=0; i<mForegroundProcesses.size(); i++) {
9020 ProcessRecord r = mPidsSelfLocked.get(
9021 mForegroundProcesses.valueAt(i).pid);
9022 if (dumpPackage != null && (r == null
9023 || !dumpPackage.equals(r.info.packageName))) {
9024 continue;
9025 }
9026 if (!printed) {
9027 if (needSep) pw.println(" ");
9028 needSep = true;
9029 pw.println(" Foreground Processes:");
9030 printed = true;
9031 }
9032 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i));
9033 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i));
9034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009036 }
9037
9038 if (mPersistentStartingProcesses.size() > 0) {
9039 if (needSep) pw.println(" ");
9040 needSep = true;
9041 pw.println(" Persisent processes that are starting:");
9042 dumpProcessList(pw, this, mPersistentStartingProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009043 "Starting Norm", "Restarting PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009045
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009046 if (mRemovedProcesses.size() > 0) {
9047 if (needSep) pw.println(" ");
9048 needSep = true;
9049 pw.println(" Processes that are being removed:");
9050 dumpProcessList(pw, this, mRemovedProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009051 "Removed Norm", "Removed PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009052 }
9053
9054 if (mProcessesOnHold.size() > 0) {
9055 if (needSep) pw.println(" ");
9056 needSep = true;
9057 pw.println(" Processes that are on old until the system is ready:");
9058 dumpProcessList(pw, this, mProcessesOnHold, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009059 "OnHold Norm", "OnHold PERS", dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009061
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009062 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009063
9064 if (mProcessCrashTimes.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009065 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009066 long now = SystemClock.uptimeMillis();
9067 for (Map.Entry<String, SparseArray<Long>> procs
9068 : mProcessCrashTimes.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009069 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009070 SparseArray<Long> uids = procs.getValue();
9071 final int N = uids.size();
9072 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009073 int puid = uids.keyAt(i);
9074 ProcessRecord r = mProcessNames.get(pname, puid);
9075 if (dumpPackage != null && (r == null
9076 || !dumpPackage.equals(r.info.packageName))) {
9077 continue;
9078 }
9079 if (!printed) {
9080 if (needSep) pw.println(" ");
9081 needSep = true;
9082 pw.println(" Time since processes crashed:");
9083 printed = true;
9084 }
9085 pw.print(" Process "); pw.print(pname);
9086 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009087 pw.print(": last crashed ");
Dianne Hackborn27ff9132012-03-06 14:57:58 -08009088 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
9089 pw.println(" ago");
Dianne Hackbornfd12af42009-08-27 00:44:33 -07009090 }
9091 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009093
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009094 if (mBadProcesses.getMap().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009095 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009096 for (Map.Entry<String, SparseArray<Long>> procs
9097 : mBadProcesses.getMap().entrySet()) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009098 String pname = procs.getKey();
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009099 SparseArray<Long> uids = procs.getValue();
9100 final int N = uids.size();
9101 for (int i=0; i<N; i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009102 int puid = uids.keyAt(i);
9103 ProcessRecord r = mProcessNames.get(pname, puid);
9104 if (dumpPackage != null && (r == null
9105 || !dumpPackage.equals(r.info.packageName))) {
9106 continue;
9107 }
9108 if (!printed) {
9109 if (needSep) pw.println(" ");
9110 needSep = true;
9111 pw.println(" Bad processes:");
9112 }
9113 pw.print(" Bad process "); pw.print(pname);
9114 pw.print(" uid "); pw.print(puid);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009115 pw.print(": crashed at time ");
9116 pw.println(uids.valueAt(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009117 }
9118 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009120
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009121 pw.println();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07009122 pw.println(" mStartedUsers:");
9123 for (int i=0; i<mStartedUsers.size(); i++) {
9124 UserStartedState uss = mStartedUsers.valueAt(i);
9125 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
9126 pw.println(":");
9127 uss.dump(" ", pw);
9128 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009129 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009130 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn50685602011-12-01 12:23:37 -08009131 if (dumpAll) {
9132 StringBuilder sb = new StringBuilder(128);
9133 sb.append(" mPreviousProcessVisibleTime: ");
9134 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb);
9135 pw.println(sb);
9136 }
Dianne Hackborn860755f2010-06-03 18:47:52 -07009137 if (mHeavyWeightProcess != null) {
9138 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9139 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009140 pw.println(" mConfiguration: " + mConfiguration);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009141 if (dumpAll) {
9142 pw.println(" mConfigWillChange: " + mMainStack.mConfigWillChange);
Dianne Hackborn3d0724d2011-05-12 15:39:41 -07009143 if (mCompatModePackages.getPackages().size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009144 boolean printed = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009145 for (Map.Entry<String, Integer> entry
9146 : mCompatModePackages.getPackages().entrySet()) {
9147 String pkg = entry.getKey();
9148 int mode = entry.getValue();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009149 if (dumpPackage != null && !dumpPackage.equals(pkg)) {
9150 continue;
9151 }
9152 if (!printed) {
9153 pw.println(" mScreenCompatPackages:");
9154 printed = true;
9155 }
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07009156 pw.print(" "); pw.print(pkg); pw.print(": ");
9157 pw.print(mode); pw.println();
9158 }
Dianne Hackbornaa9d84c2011-05-09 19:00:59 -07009159 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009160 }
Dianne Hackbornff5b1582012-04-12 17:24:07 -07009161 if (mSleeping || mWentToSleep || mLockScreenShown) {
9162 pw.println(" mSleeping=" + mSleeping + " mWentToSleep=" + mWentToSleep
9163 + " mLockScreenShown " + mLockScreenShown);
9164 }
9165 if (mShuttingDown) {
9166 pw.println(" mShuttingDown=" + mShuttingDown);
9167 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009168 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient
9169 || mOrigWaitForDebugger) {
9170 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp
9171 + " mDebugTransient=" + mDebugTransient
9172 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger);
9173 }
Siva Velusamy92a8b222012-03-09 16:24:04 -08009174 if (mOpenGlTraceApp != null) {
9175 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp);
9176 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07009177 if (mProfileApp != null || mProfileProc != null || mProfileFile != null
9178 || mProfileFd != null) {
9179 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc);
9180 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd);
9181 pw.println(" mProfileType=" + mProfileType + " mAutoStopProfiler="
9182 + mAutoStopProfiler);
9183 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009184 if (mAlwaysFinishActivities || mController != null) {
9185 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities
9186 + " mController=" + mController);
9187 }
9188 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009189 pw.println(" Total persistent processes: " + numPers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009190 pw.println(" mStartRunning=" + mStartRunning
Dianne Hackborn8891fdc2010-09-20 20:44:46 -07009191 + " mProcessesReady=" + mProcessesReady
9192 + " mSystemReady=" + mSystemReady);
9193 pw.println(" mBooting=" + mBooting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009194 + " mBooted=" + mBooted
9195 + " mFactoryTest=" + mFactoryTest);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009196 pw.print(" mLastPowerCheckRealtime=");
9197 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw);
9198 pw.println("");
9199 pw.print(" mLastPowerCheckUptime=");
9200 TimeUtils.formatDuration(mLastPowerCheckUptime, pw);
9201 pw.println("");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07009202 pw.println(" mGoingToSleep=" + mMainStack.mGoingToSleep);
9203 pw.println(" mLaunchingActivity=" + mMainStack.mLaunchingActivity);
Dianne Hackborn906497c2010-05-10 15:57:38 -07009204 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009205 pw.println(" mNumNonHiddenProcs=" + mNumNonHiddenProcs
9206 + " mNumHiddenProcs=" + mNumHiddenProcs
9207 + " mNumServiceProcs=" + mNumServiceProcs
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009208 + " mNewNumServiceProcs=" + mNewNumServiceProcs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009209 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009210
9211 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009212 }
9213
Dianne Hackborn287952c2010-09-22 22:34:31 -07009214 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009215 int opti, boolean needSep, boolean dumpAll, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009216 if (mProcessesToGc.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009217 boolean printed = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009218 long now = SystemClock.uptimeMillis();
9219 for (int i=0; i<mProcessesToGc.size(); i++) {
9220 ProcessRecord proc = mProcessesToGc.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009221 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) {
9222 continue;
9223 }
9224 if (!printed) {
9225 if (needSep) pw.println(" ");
9226 needSep = true;
9227 pw.println(" Processes that are waiting to GC:");
9228 printed = true;
9229 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009230 pw.print(" Process "); pw.println(proc);
9231 pw.print(" lowMem="); pw.print(proc.reportLowMemory);
9232 pw.print(", last gced=");
9233 pw.print(now-proc.lastRequestedGc);
9234 pw.print(" ms ago, last lowMem=");
9235 pw.print(now-proc.lastLowMemory);
9236 pw.println(" ms ago");
9237
9238 }
9239 }
9240 return needSep;
9241 }
9242
9243 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args,
9244 int opti, boolean dumpAll) {
9245 boolean needSep = false;
9246
9247 if (mLruProcesses.size() > 0) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009248 if (needSep) pw.println(" ");
9249 needSep = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009250 pw.println(" OOM levels:");
Dianne Hackborn7d608422011-08-07 16:24:18 -07009251 pw.print(" SYSTEM_ADJ: "); pw.println(ProcessList.SYSTEM_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009252 pw.print(" PERSISTENT_PROC_ADJ: "); pw.println(ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009253 pw.print(" FOREGROUND_APP_ADJ: "); pw.println(ProcessList.FOREGROUND_APP_ADJ);
9254 pw.print(" VISIBLE_APP_ADJ: "); pw.println(ProcessList.VISIBLE_APP_ADJ);
9255 pw.print(" PERCEPTIBLE_APP_ADJ: "); pw.println(ProcessList.PERCEPTIBLE_APP_ADJ);
9256 pw.print(" HEAVY_WEIGHT_APP_ADJ: "); pw.println(ProcessList.HEAVY_WEIGHT_APP_ADJ);
9257 pw.print(" BACKUP_APP_ADJ: "); pw.println(ProcessList.BACKUP_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009258 pw.print(" SERVICE_ADJ: "); pw.println(ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009259 pw.print(" HOME_APP_ADJ: "); pw.println(ProcessList.HOME_APP_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009260 pw.print(" PREVIOUS_APP_ADJ: "); pw.println(ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009261 pw.print(" SERVICE_B_ADJ: "); pw.println(ProcessList.SERVICE_B_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009262 pw.print(" HIDDEN_APP_MIN_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009263 pw.print(" HIDDEN_APP_MAX_ADJ: "); pw.println(ProcessList.HIDDEN_APP_MAX_ADJ);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009264
9265 if (needSep) pw.println(" ");
9266 needSep = true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009267 pw.println(" Process OOM control:");
Dianne Hackborn905577f2011-09-07 18:31:28 -07009268 dumpProcessOomList(pw, this, mLruProcesses, " ",
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009269 "Proc", "PERS", true, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009270 needSep = true;
9271 }
9272
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009273 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009274
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009275 pw.println();
Dianne Hackborn287952c2010-09-22 22:34:31 -07009276 pw.println(" mHomeProcess: " + mHomeProcess);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009277 pw.println(" mPreviousProcess: " + mPreviousProcess);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009278 if (mHeavyWeightProcess != null) {
9279 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess);
9280 }
9281
9282 return true;
9283 }
9284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009285 /**
9286 * There are three ways to call this:
Marco Nelissen18cb2872011-11-15 11:19:53 -08009287 * - no provider specified: dump all the providers
9288 * - a flattened component name that matched an existing provider was specified as the
9289 * first arg: dump that one provider
9290 * - the first arg isn't the flattened component name of an existing provider:
9291 * dump all providers whose component contains the first arg as a substring
9292 */
9293 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9294 int opti, boolean dumpAll) {
Marco Nelissende7408c2012-02-08 14:57:38 -08009295 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll);
Marco Nelissen18cb2872011-11-15 11:19:53 -08009296 }
9297
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009298 static class ItemMatcher {
9299 ArrayList<ComponentName> components;
9300 ArrayList<String> strings;
9301 ArrayList<Integer> objects;
9302 boolean all;
9303
9304 ItemMatcher() {
9305 all = true;
9306 }
9307
9308 void build(String name) {
9309 ComponentName componentName = ComponentName.unflattenFromString(name);
9310 if (componentName != null) {
9311 if (components == null) {
9312 components = new ArrayList<ComponentName>();
9313 }
9314 components.add(componentName);
9315 all = false;
9316 } else {
9317 int objectId = 0;
9318 // Not a '/' separated full component name; maybe an object ID?
9319 try {
9320 objectId = Integer.parseInt(name, 16);
9321 if (objects == null) {
9322 objects = new ArrayList<Integer>();
9323 }
9324 objects.add(objectId);
9325 all = false;
9326 } catch (RuntimeException e) {
9327 // Not an integer; just do string match.
9328 if (strings == null) {
9329 strings = new ArrayList<String>();
9330 }
9331 strings.add(name);
9332 all = false;
9333 }
9334 }
9335 }
9336
9337 int build(String[] args, int opti) {
9338 for (; opti<args.length; opti++) {
9339 String name = args[opti];
9340 if ("--".equals(name)) {
9341 return opti+1;
9342 }
9343 build(name);
9344 }
9345 return opti;
9346 }
9347
9348 boolean match(Object object, ComponentName comp) {
9349 if (all) {
9350 return true;
9351 }
9352 if (components != null) {
9353 for (int i=0; i<components.size(); i++) {
9354 if (components.get(i).equals(comp)) {
9355 return true;
9356 }
9357 }
9358 }
9359 if (objects != null) {
9360 for (int i=0; i<objects.size(); i++) {
9361 if (System.identityHashCode(object) == objects.get(i)) {
9362 return true;
9363 }
9364 }
9365 }
9366 if (strings != null) {
9367 String flat = comp.flattenToString();
9368 for (int i=0; i<strings.size(); i++) {
9369 if (flat.contains(strings.get(i))) {
9370 return true;
9371 }
9372 }
9373 }
9374 return false;
9375 }
9376 }
9377
Dianne Hackborn625ac272010-09-17 18:29:22 -07009378 /**
9379 * There are three things that cmd can be:
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009380 * - a flattened component name that matches an existing activity
Dianne Hackborn625ac272010-09-17 18:29:22 -07009381 * - the cmd arg isn't the flattened component name of an existing activity:
9382 * dump all activity whose component contains the cmd as a substring
9383 * - A hex number of the ActivityRecord object instance.
9384 */
9385 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args,
9386 int opti, boolean dumpAll) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009387 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009388
9389 if ("all".equals(name)) {
9390 synchronized (this) {
9391 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn625ac272010-09-17 18:29:22 -07009392 activities.add(r1);
9393 }
9394 }
Dianne Hackbornf9302322011-06-14 18:36:14 -07009395 } else if ("top".equals(name)) {
9396 synchronized (this) {
9397 final int N = mMainStack.mHistory.size();
9398 if (N > 0) {
9399 activities.add((ActivityRecord)mMainStack.mHistory.get(N-1));
9400 }
9401 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009402 } else {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009403 ItemMatcher matcher = new ItemMatcher();
9404 matcher.build(name);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009405
9406 synchronized (this) {
9407 for (ActivityRecord r1 : (ArrayList<ActivityRecord>)mMainStack.mHistory) {
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009408 if (matcher.match(r1, r1.intent.getComponent())) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009409 activities.add(r1);
9410 }
9411 }
9412 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009413 }
9414
9415 if (activities.size() <= 0) {
9416 return false;
9417 }
9418
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009419 String[] newArgs = new String[args.length - opti];
9420 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti);
9421
Dianne Hackborn30d71892010-12-11 10:37:55 -08009422 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009423 boolean needSep = false;
Dianne Hackborn30d71892010-12-11 10:37:55 -08009424 for (int i=activities.size()-1; i>=0; i--) {
9425 ActivityRecord r = (ActivityRecord)activities.get(i);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009426 if (needSep) {
9427 pw.println();
9428 }
9429 needSep = true;
9430 synchronized (this) {
9431 if (lastTask != r.task) {
9432 lastTask = r.task;
9433 pw.print("TASK "); pw.print(lastTask.affinity);
9434 pw.print(" id="); pw.println(lastTask.taskId);
9435 if (dumpAll) {
9436 lastTask.dump(pw, " ");
9437 }
Dianne Hackborn30d71892010-12-11 10:37:55 -08009438 }
9439 }
9440 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009441 }
9442 return true;
9443 }
9444
9445 /**
9446 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if
9447 * there is a thread associated with the activity.
9448 */
Dianne Hackborn30d71892010-12-11 10:37:55 -08009449 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw,
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009450 final ActivityRecord r, String[] args, boolean dumpAll) {
9451 String innerPrefix = prefix + " ";
Dianne Hackborn30d71892010-12-11 10:37:55 -08009452 synchronized (this) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009453 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName);
9454 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r)));
9455 pw.print(" pid=");
Dianne Hackborn30d71892010-12-11 10:37:55 -08009456 if (r.app != null) pw.println(r.app.pid);
9457 else pw.println("(not running)");
9458 if (dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009459 r.dump(pw, innerPrefix);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009460 }
Dianne Hackborn625ac272010-09-17 18:29:22 -07009461 }
9462 if (r.app != null && r.app.thread != null) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009463 // flush anything that is already in the PrintWriter since the thread is going
9464 // to write to the file descriptor directly
9465 pw.flush();
Dianne Hackborn625ac272010-09-17 18:29:22 -07009466 try {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009467 TransferPipe tp = new TransferPipe();
9468 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009469 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9470 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009471 tp.go(fd);
9472 } finally {
9473 tp.kill();
9474 }
9475 } catch (IOException e) {
9476 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
Dianne Hackborn625ac272010-09-17 18:29:22 -07009477 } catch (RemoteException e) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009478 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
Dianne Hackborn625ac272010-09-17 18:29:22 -07009479 }
9480 }
9481 }
9482
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009483 boolean dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009484 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009485 boolean needSep = false;
Dianne Hackborn786b4402012-08-27 15:14:02 -07009486 boolean onlyHistory = false;
9487
9488 if ("history".equals(dumpPackage)) {
9489 onlyHistory = true;
9490 dumpPackage = null;
9491 }
9492
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009493 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)");
Dianne Hackborn786b4402012-08-27 15:14:02 -07009494 if (!onlyHistory && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009495 if (mRegisteredReceivers.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009496 boolean printed = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009497 Iterator it = mRegisteredReceivers.values().iterator();
9498 while (it.hasNext()) {
9499 ReceiverList r = (ReceiverList)it.next();
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009500 if (dumpPackage != null && (r.app == null ||
9501 !dumpPackage.equals(r.app.info.packageName))) {
9502 continue;
9503 }
9504 if (!printed) {
9505 pw.println(" Registered Receivers:");
9506 needSep = true;
9507 printed = true;
9508 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009509 pw.print(" * "); pw.println(r);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009510 r.dump(pw, " ");
9511 }
9512 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009513
9514 if (mReceiverResolver.dump(pw, needSep ?
9515 "\n Receiver Resolver Table:" : " Receiver Resolver Table:",
9516 " ", dumpPackage, false)) {
9517 needSep = true;
9518 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009519 }
Christopher Tatef46723b2012-01-26 14:19:24 -08009520
9521 for (BroadcastQueue q : mBroadcastQueues) {
9522 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009524
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009525 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009526
Dianne Hackborn786b4402012-08-27 15:14:02 -07009527 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009528 for (int user=0; user<mStickyBroadcasts.size(); user++) {
9529 if (needSep) {
9530 pw.println();
9531 }
9532 needSep = true;
9533 pw.print(" Sticky broadcasts for user ");
9534 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":");
9535 StringBuilder sb = new StringBuilder(128);
9536 for (Map.Entry<String, ArrayList<Intent>> ent
9537 : mStickyBroadcasts.valueAt(user).entrySet()) {
9538 pw.print(" * Sticky action "); pw.print(ent.getKey());
9539 if (dumpAll) {
9540 pw.println(":");
9541 ArrayList<Intent> intents = ent.getValue();
9542 final int N = intents.size();
9543 for (int i=0; i<N; i++) {
9544 sb.setLength(0);
9545 sb.append(" Intent: ");
9546 intents.get(i).toShortString(sb, false, true, false, false);
9547 pw.println(sb.toString());
9548 Bundle bundle = intents.get(i).getExtras();
9549 if (bundle != null) {
9550 pw.print(" ");
9551 pw.println(bundle.toString());
9552 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009553 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07009554 } else {
9555 pw.println("");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009556 }
9557 }
9558 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009559 }
9560
Dianne Hackborn786b4402012-08-27 15:14:02 -07009561 if (!onlyHistory && dumpAll) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009562 pw.println();
Christopher Tatef46723b2012-01-26 14:19:24 -08009563 for (BroadcastQueue queue : mBroadcastQueues) {
9564 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]="
9565 + queue.mBroadcastsScheduled);
9566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009567 pw.println(" mHandler:");
9568 mHandler.dump(new PrintWriterPrinter(pw), " ");
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009569 needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009570 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009571
9572 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009573 }
9574
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009575 boolean dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009576 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07009577 boolean needSep = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009578
Dianne Hackborn1c9b2602011-08-19 14:08:43 -07009579 ItemMatcher matcher = new ItemMatcher();
9580 matcher.build(args, opti);
9581
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009582 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)");
Amith Yamasani742a6712011-05-04 14:49:28 -07009583
9584 mProviderMap.dumpProvidersLocked(pw, dumpAll);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009585
9586 if (mLaunchingProviders.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009587 boolean printed = false;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009588 for (int i=mLaunchingProviders.size()-1; i>=0; i--) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009589 ContentProviderRecord r = mLaunchingProviders.get(i);
9590 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) {
9591 continue;
9592 }
9593 if (!printed) {
9594 if (needSep) pw.println(" ");
9595 needSep = true;
9596 pw.println(" Launching content providers:");
9597 printed = true;
9598 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009599 pw.print(" Launching #"); pw.print(i); pw.print(": ");
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009600 pw.println(r);
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009601 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009602 }
9603
9604 if (mGrantedUriPermissions.size() > 0) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009605 if (needSep) pw.println();
9606 needSep = true;
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009607 pw.println("Granted Uri Permissions:");
9608 for (int i=0; i<mGrantedUriPermissions.size(); i++) {
9609 int uid = mGrantedUriPermissions.keyAt(i);
9610 HashMap<Uri, UriPermission> perms
9611 = mGrantedUriPermissions.valueAt(i);
9612 pw.print(" * UID "); pw.print(uid);
9613 pw.println(" holds:");
9614 for (UriPermission perm : perms.values()) {
9615 pw.print(" "); pw.println(perm);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009616 if (dumpAll) {
9617 perm.dump(pw, " ");
9618 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009619 }
9620 }
9621 needSep = true;
9622 }
9623
9624 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009625 }
9626
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009627 boolean dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009628 int opti, boolean dumpAll, String dumpPackage) {
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009629 boolean needSep = false;
9630
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009631 if (mIntentSenderRecords.size() > 0) {
9632 boolean printed = false;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009633 Iterator<WeakReference<PendingIntentRecord>> it
9634 = mIntentSenderRecords.values().iterator();
9635 while (it.hasNext()) {
9636 WeakReference<PendingIntentRecord> ref = it.next();
9637 PendingIntentRecord rec = ref != null ? ref.get(): null;
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009638 if (dumpPackage != null && (rec == null
9639 || !dumpPackage.equals(rec.key.packageName))) {
9640 continue;
9641 }
9642 if (!printed) {
9643 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)");
9644 printed = true;
9645 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009646 needSep = true;
9647 if (rec != null) {
9648 pw.print(" * "); pw.println(rec);
9649 if (dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009650 rec.dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009651 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009652 } else {
9653 pw.print(" * "); pw.println(ref);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009654 }
9655 }
9656 }
Dianne Hackbornc59411b2009-12-21 20:10:14 -08009657
9658 return needSep;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009659 }
9660
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009661 private static final void dumpHistoryList(FileDescriptor fd, PrintWriter pw, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009662 String prefix, String label, boolean complete, boolean brief, boolean client,
9663 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009664 TaskRecord lastTask = null;
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009665 boolean needNL = false;
9666 final String innerPrefix = prefix + " ";
9667 final String[] args = new String[0];
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009668 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009669 final ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009670 if (dumpPackage != null && !dumpPackage.equals(r.packageName)) {
9671 continue;
9672 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07009673 final boolean full = !brief && (complete || !r.isInHistory());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009674 if (needNL) {
9675 pw.println(" ");
9676 needNL = false;
9677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009678 if (lastTask != r.task) {
9679 lastTask = r.task;
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009680 pw.print(prefix);
9681 pw.print(full ? "* " : " ");
9682 pw.println(lastTask);
9683 if (full) {
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009684 lastTask.dump(pw, prefix + " ");
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009685 } else if (complete) {
9686 // Complete + brief == give a summary. Isn't that obvious?!?
9687 if (lastTask.intent != null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009688 pw.print(prefix); pw.print(" ");
Dianne Hackborn21c241e2012-03-08 13:57:23 -08009689 pw.println(lastTask.intent.toInsecureStringWithClip());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009690 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009692 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07009693 pw.print(prefix); pw.print(full ? " * " : " "); pw.print(label);
9694 pw.print(" #"); pw.print(i); pw.print(": ");
9695 pw.println(r);
9696 if (full) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009697 r.dump(pw, innerPrefix);
9698 } else if (complete) {
9699 // Complete + brief == give a summary. Isn't that obvious?!?
Dianne Hackborn90c52de2011-09-23 12:57:44 -07009700 pw.print(innerPrefix); pw.println(r.intent.toInsecureString());
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009701 if (r.app != null) {
9702 pw.print(innerPrefix); pw.println(r.app);
9703 }
9704 }
9705 if (client && r.app != null && r.app.thread != null) {
9706 // flush anything that is already in the PrintWriter since the thread is going
9707 // to write to the file descriptor directly
9708 pw.flush();
9709 try {
9710 TransferPipe tp = new TransferPipe();
9711 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08009712 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(),
9713 r.appToken, innerPrefix, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009714 // Short timeout, since blocking here can
9715 // deadlock with the application.
9716 tp.go(fd, 2000);
9717 } finally {
9718 tp.kill();
9719 }
9720 } catch (IOException e) {
9721 pw.println(innerPrefix + "Failure while dumping the activity: " + e);
9722 } catch (RemoteException e) {
9723 pw.println(innerPrefix + "Got a RemoteException while dumping the activity");
9724 }
9725 needNL = true;
Dianne Hackbornf210d6b2009-04-13 18:42:49 -07009726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009727 }
9728 }
9729
Dianne Hackborn09c916b2009-12-08 14:50:51 -08009730 private static String buildOomTag(String prefix, String space, int val, int base) {
9731 if (val == base) {
9732 if (space == null) return prefix;
9733 return prefix + " ";
9734 }
9735 return prefix + "+" + Integer.toString(val-base);
9736 }
9737
9738 private static final int dumpProcessList(PrintWriter pw,
9739 ActivityManagerService service, List list,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009740 String prefix, String normalLabel, String persistentLabel,
9741 String dumpPackage) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009742 int numPers = 0;
Dianne Hackborn32907cf2010-06-10 17:50:20 -07009743 final int N = list.size()-1;
9744 for (int i=N; i>=0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009745 ProcessRecord r = (ProcessRecord)list.get(i);
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009746 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9747 continue;
9748 }
Dianne Hackborn287952c2010-09-22 22:34:31 -07009749 pw.println(String.format("%s%s #%2d: %s",
9750 prefix, (r.persistent ? persistentLabel : normalLabel),
9751 i, r.toString()));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009752 if (r.persistent) {
9753 numPers++;
9754 }
9755 }
9756 return numPers;
9757 }
9758
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009759 private static final boolean dumpProcessOomList(PrintWriter pw,
Dianne Hackborn905577f2011-09-07 18:31:28 -07009760 ActivityManagerService service, List<ProcessRecord> origList,
Dianne Hackborn287952c2010-09-22 22:34:31 -07009761 String prefix, String normalLabel, String persistentLabel,
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009762 boolean inclDetails, String dumpPackage) {
Dianne Hackborn287952c2010-09-22 22:34:31 -07009763
Dianne Hackborn905577f2011-09-07 18:31:28 -07009764 ArrayList<Pair<ProcessRecord, Integer>> list
9765 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size());
9766 for (int i=0; i<origList.size(); i++) {
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009767 ProcessRecord r = origList.get(i);
9768 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) {
9769 continue;
9770 }
Dianne Hackborn905577f2011-09-07 18:31:28 -07009771 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i));
9772 }
9773
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009774 if (list.size() <= 0) {
9775 return false;
9776 }
9777
Dianne Hackborn905577f2011-09-07 18:31:28 -07009778 Comparator<Pair<ProcessRecord, Integer>> comparator
9779 = new Comparator<Pair<ProcessRecord, Integer>>() {
9780 @Override
9781 public int compare(Pair<ProcessRecord, Integer> object1,
9782 Pair<ProcessRecord, Integer> object2) {
9783 if (object1.first.setAdj != object2.first.setAdj) {
9784 return object1.first.setAdj > object2.first.setAdj ? -1 : 1;
9785 }
9786 if (object1.second.intValue() != object2.second.intValue()) {
9787 return object1.second.intValue() > object2.second.intValue() ? -1 : 1;
9788 }
9789 return 0;
9790 }
9791 };
9792
9793 Collections.sort(list, comparator);
9794
Dianne Hackborn287952c2010-09-22 22:34:31 -07009795 final long curRealtime = SystemClock.elapsedRealtime();
9796 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime;
9797 final long curUptime = SystemClock.uptimeMillis();
9798 final long uptimeSince = curUptime - service.mLastPowerCheckUptime;
9799
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009800 for (int i=list.size()-1; i>=0; i--) {
Dianne Hackborn905577f2011-09-07 18:31:28 -07009801 ProcessRecord r = list.get(i).first;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009802 String oomAdj;
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009803 if (r.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn7d608422011-08-07 16:24:18 -07009804 oomAdj = buildOomTag("bak", " ", r.setAdj, ProcessList.HIDDEN_APP_MIN_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009805 } else if (r.setAdj >= ProcessList.SERVICE_B_ADJ) {
9806 oomAdj = buildOomTag("svcb ", null, r.setAdj, ProcessList.SERVICE_B_ADJ);
Dianne Hackbornf35fe232011-11-01 19:25:20 -07009807 } else if (r.setAdj >= ProcessList.PREVIOUS_APP_ADJ) {
9808 oomAdj = buildOomTag("prev ", null, r.setAdj, ProcessList.PREVIOUS_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009809 } else if (r.setAdj >= ProcessList.HOME_APP_ADJ) {
9810 oomAdj = buildOomTag("home ", null, r.setAdj, ProcessList.HOME_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009811 } else if (r.setAdj >= ProcessList.SERVICE_ADJ) {
9812 oomAdj = buildOomTag("svc ", null, r.setAdj, ProcessList.SERVICE_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009813 } else if (r.setAdj >= ProcessList.BACKUP_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -08009814 oomAdj = buildOomTag("bkup ", null, r.setAdj, ProcessList.BACKUP_APP_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009815 } else if (r.setAdj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
9816 oomAdj = buildOomTag("hvy ", null, r.setAdj, ProcessList.HEAVY_WEIGHT_APP_ADJ);
9817 } else if (r.setAdj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
9818 oomAdj = buildOomTag("prcp ", null, r.setAdj, ProcessList.PERCEPTIBLE_APP_ADJ);
9819 } else if (r.setAdj >= ProcessList.VISIBLE_APP_ADJ) {
9820 oomAdj = buildOomTag("vis ", null, r.setAdj, ProcessList.VISIBLE_APP_ADJ);
9821 } else if (r.setAdj >= ProcessList.FOREGROUND_APP_ADJ) {
9822 oomAdj = buildOomTag("fore ", null, r.setAdj, ProcessList.FOREGROUND_APP_ADJ);
Dianne Hackborne02c88a2011-10-28 13:58:15 -07009823 } else if (r.setAdj >= ProcessList.PERSISTENT_PROC_ADJ) {
9824 oomAdj = buildOomTag("pers ", null, r.setAdj, ProcessList.PERSISTENT_PROC_ADJ);
Dianne Hackborn7d608422011-08-07 16:24:18 -07009825 } else if (r.setAdj >= ProcessList.SYSTEM_ADJ) {
9826 oomAdj = buildOomTag("sys ", null, r.setAdj, ProcessList.SYSTEM_ADJ);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009827 } else {
9828 oomAdj = Integer.toString(r.setAdj);
9829 }
9830 String schedGroup;
9831 switch (r.setSchedGroup) {
9832 case Process.THREAD_GROUP_BG_NONINTERACTIVE:
9833 schedGroup = "B";
9834 break;
9835 case Process.THREAD_GROUP_DEFAULT:
9836 schedGroup = "F";
9837 break;
9838 default:
9839 schedGroup = Integer.toString(r.setSchedGroup);
9840 break;
9841 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07009842 String foreground;
9843 if (r.foregroundActivities) {
9844 foreground = "A";
9845 } else if (r.foregroundServices) {
9846 foreground = "S";
9847 } else {
9848 foreground = " ";
9849 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07009850 pw.println(String.format("%s%s #%2d: adj=%s/%s%s trm=%2d %s (%s)",
Dianne Hackborn287952c2010-09-22 22:34:31 -07009851 prefix, (r.persistent ? persistentLabel : normalLabel),
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009852 (origList.size()-1)-list.get(i).second, oomAdj, schedGroup,
9853 foreground, r.trimMemoryLevel, r.toShortString(), r.adjType));
Dianne Hackborn287952c2010-09-22 22:34:31 -07009854 if (r.adjSource != null || r.adjTarget != null) {
9855 pw.print(prefix);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009856 pw.print(" ");
Dianne Hackborn287952c2010-09-22 22:34:31 -07009857 if (r.adjTarget instanceof ComponentName) {
9858 pw.print(((ComponentName)r.adjTarget).flattenToShortString());
9859 } else if (r.adjTarget != null) {
9860 pw.print(r.adjTarget.toString());
9861 } else {
9862 pw.print("{null}");
9863 }
9864 pw.print("<=");
9865 if (r.adjSource instanceof ProcessRecord) {
9866 pw.print("Proc{");
9867 pw.print(((ProcessRecord)r.adjSource).toShortString());
9868 pw.println("}");
9869 } else if (r.adjSource != null) {
9870 pw.println(r.adjSource.toString());
9871 } else {
9872 pw.println("{null}");
9873 }
9874 }
9875 if (inclDetails) {
9876 pw.print(prefix);
9877 pw.print(" ");
9878 pw.print("oom: max="); pw.print(r.maxAdj);
9879 pw.print(" hidden="); pw.print(r.hiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -07009880 pw.print(" empty="); pw.print(r.emptyAdj);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009881 pw.print(" curRaw="); pw.print(r.curRawAdj);
9882 pw.print(" setRaw="); pw.print(r.setRawAdj);
9883 pw.print(" cur="); pw.print(r.curAdj);
9884 pw.print(" set="); pw.println(r.setAdj);
9885 pw.print(prefix);
9886 pw.print(" ");
9887 pw.print("keeping="); pw.print(r.keeping);
9888 pw.print(" hidden="); pw.print(r.hidden);
Dianne Hackbornc68c9132011-07-29 01:25:18 -07009889 pw.print(" empty="); pw.print(r.empty);
9890 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient);
Dianne Hackborn287952c2010-09-22 22:34:31 -07009891
9892 if (!r.keeping) {
9893 if (r.lastWakeTime != 0) {
9894 long wtime;
9895 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics();
9896 synchronized (stats) {
9897 wtime = stats.getProcessWakeTime(r.info.uid,
9898 r.pid, curRealtime);
9899 }
9900 long timeUsed = wtime - r.lastWakeTime;
9901 pw.print(prefix);
9902 pw.print(" ");
9903 pw.print("keep awake over ");
9904 TimeUtils.formatDuration(realtimeSince, pw);
9905 pw.print(" used ");
9906 TimeUtils.formatDuration(timeUsed, pw);
9907 pw.print(" (");
9908 pw.print((timeUsed*100)/realtimeSince);
9909 pw.println("%)");
9910 }
9911 if (r.lastCpuTime != 0) {
9912 long timeUsed = r.curCpuTime - r.lastCpuTime;
9913 pw.print(prefix);
9914 pw.print(" ");
9915 pw.print("run cpu over ");
9916 TimeUtils.formatDuration(uptimeSince, pw);
9917 pw.print(" used ");
9918 TimeUtils.formatDuration(timeUsed, pw);
9919 pw.print(" (");
9920 pw.print((timeUsed*100)/uptimeSince);
9921 pw.println("%)");
9922 }
9923 }
9924 }
9925 }
Dianne Hackbornee9aef02011-11-16 13:21:46 -08009926 return true;
Dianne Hackborn287952c2010-09-22 22:34:31 -07009927 }
9928
Dianne Hackbornb437e092011-08-05 17:50:29 -07009929 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, String[] args) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009930 ArrayList<ProcessRecord> procs;
9931 synchronized (this) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009932 if (args != null && args.length > start
9933 && args[start].charAt(0) != '-') {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009934 procs = new ArrayList<ProcessRecord>();
9935 int pid = -1;
9936 try {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009937 pid = Integer.parseInt(args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009938 } catch (NumberFormatException e) {
9939
9940 }
9941 for (int i=mLruProcesses.size()-1; i>=0; i--) {
9942 ProcessRecord proc = mLruProcesses.get(i);
9943 if (proc.pid == pid) {
9944 procs.add(proc);
Dianne Hackbornb437e092011-08-05 17:50:29 -07009945 } else if (proc.processName.equals(args[start])) {
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009946 procs.add(proc);
9947 }
9948 }
9949 if (procs.size() <= 0) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009950 pw.println("No process found for: " + args[start]);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009951 return null;
9952 }
9953 } else {
9954 procs = new ArrayList<ProcessRecord>(mLruProcesses);
9955 }
9956 }
9957 return procs;
9958 }
9959
9960 final void dumpGraphicsHardwareUsage(FileDescriptor fd,
9961 PrintWriter pw, String[] args) {
Dianne Hackbornb437e092011-08-05 17:50:29 -07009962 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009963 if (procs == null) {
9964 return;
9965 }
9966
9967 long uptime = SystemClock.uptimeMillis();
9968 long realtime = SystemClock.elapsedRealtime();
9969 pw.println("Applications Graphics Acceleration Info:");
9970 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
9971
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009972 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
9973 ProcessRecord r = procs.get(i);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009974 if (r.thread != null) {
9975 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **");
9976 pw.flush();
9977 try {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009978 TransferPipe tp = new TransferPipe();
9979 try {
9980 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args);
9981 tp.go(fd);
9982 } finally {
9983 tp.kill();
9984 }
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009985 } catch (IOException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009986 pw.println("Failure while dumping the app: " + r);
Dianne Hackborne17aeb32011-04-07 15:11:57 -07009987 pw.flush();
Chet Haase9c1e23b2011-03-24 10:51:31 -07009988 } catch (RemoteException e) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -07009989 pw.println("Got a RemoteException while dumping the app " + r);
Chet Haase9c1e23b2011-03-24 10:51:31 -07009990 pw.flush();
9991 }
9992 }
9993 }
Chet Haase9c1e23b2011-03-24 10:51:31 -07009994 }
9995
Jeff Brown6754ba22011-12-14 20:20:01 -08009996 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) {
9997 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, args);
9998 if (procs == null) {
9999 return;
10000 }
10001
10002 pw.println("Applications Database Info:");
10003
10004 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10005 ProcessRecord r = procs.get(i);
10006 if (r.thread != null) {
10007 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **");
10008 pw.flush();
10009 try {
10010 TransferPipe tp = new TransferPipe();
10011 try {
10012 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args);
10013 tp.go(fd);
10014 } finally {
10015 tp.kill();
10016 }
10017 } catch (IOException e) {
10018 pw.println("Failure while dumping the app: " + r);
10019 pw.flush();
10020 } catch (RemoteException e) {
10021 pw.println("Got a RemoteException while dumping the app " + r);
10022 pw.flush();
10023 }
10024 }
10025 }
10026 }
10027
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010028 final static class MemItem {
10029 final String label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010030 final String shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010031 final long pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010032 final int id;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010033 ArrayList<MemItem> subitems;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010034
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010035 public MemItem(String _label, String _shortLabel, long _pss, int _id) {
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010036 label = _label;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010037 shortLabel = _shortLabel;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010038 pss = _pss;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010039 id = _id;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010040 }
10041 }
10042
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010043 static final void dumpMemItems(PrintWriter pw, String prefix, ArrayList<MemItem> items,
Dianne Hackbornb437e092011-08-05 17:50:29 -070010044 boolean sort) {
10045 if (sort) {
10046 Collections.sort(items, new Comparator<MemItem>() {
10047 @Override
10048 public int compare(MemItem lhs, MemItem rhs) {
10049 if (lhs.pss < rhs.pss) {
10050 return 1;
10051 } else if (lhs.pss > rhs.pss) {
10052 return -1;
10053 }
10054 return 0;
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010055 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010056 });
10057 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010058
10059 for (int i=0; i<items.size(); i++) {
10060 MemItem mi = items.get(i);
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010061 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010062 if (mi.subitems != null) {
10063 dumpMemItems(pw, prefix + " ", mi.subitems, true);
10064 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010065 }
10066 }
10067
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010068 // These are in KB.
10069 static final long[] DUMP_MEM_BUCKETS = new long[] {
10070 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024,
10071 120*1024, 160*1024, 200*1024,
10072 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024,
10073 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024
10074 };
10075
Dianne Hackborn672342c2011-11-29 11:29:02 -080010076 static final void appendMemBucket(StringBuilder out, long memKB, String label,
10077 boolean stackLike) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010078 int start = label.lastIndexOf('.');
10079 if (start >= 0) start++;
10080 else start = 0;
10081 int end = label.length();
10082 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) {
10083 if (DUMP_MEM_BUCKETS[i] >= memKB) {
10084 long bucket = DUMP_MEM_BUCKETS[i]/1024;
10085 out.append(bucket);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010086 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010087 out.append(label, start, end);
10088 return;
10089 }
10090 }
10091 out.append(memKB/1024);
Dianne Hackborn672342c2011-11-29 11:29:02 -080010092 out.append(stackLike ? "MB." : "MB ");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010093 out.append(label, start, end);
10094 }
10095
10096 static final int[] DUMP_MEM_OOM_ADJ = new int[] {
10097 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, ProcessList.FOREGROUND_APP_ADJ,
10098 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ,
10099 ProcessList.BACKUP_APP_ADJ, ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ,
10100 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.HIDDEN_APP_MAX_ADJ
10101 };
10102 static final String[] DUMP_MEM_OOM_LABEL = new String[] {
10103 "System", "Persistent", "Foreground",
10104 "Visible", "Perceptible", "Heavy Weight",
10105 "Backup", "A Services", "Home", "Previous",
10106 "B Services", "Background"
10107 };
10108
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010109 final void dumpApplicationMemoryUsage(FileDescriptor fd,
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010110 PrintWriter pw, String prefix, String[] args, boolean brief,
Dianne Hackborn672342c2011-11-29 11:29:02 -080010111 PrintWriter categoryPw, StringBuilder outTag, StringBuilder outStack) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010112 boolean dumpAll = false;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010113 boolean oomOnly = false;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010114
10115 int opti = 0;
10116 while (opti < args.length) {
10117 String opt = args[opti];
10118 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
10119 break;
10120 }
10121 opti++;
10122 if ("-a".equals(opt)) {
10123 dumpAll = true;
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010124 } else if ("--oom".equals(opt)) {
10125 oomOnly = true;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010126 } else if ("-h".equals(opt)) {
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010127 pw.println("meminfo dump options: [-a] [--oom] [process]");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010128 pw.println(" -a: include all available information for each process.");
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010129 pw.println(" --oom: only show processes organized by oom adj.");
Dianne Hackbornb437e092011-08-05 17:50:29 -070010130 pw.println("If [process] is specified it can be the name or ");
10131 pw.println("pid of a specific process to dump.");
10132 return;
10133 } else {
10134 pw.println("Unknown argument: " + opt + "; use -h for help");
10135 }
10136 }
10137
10138 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, args);
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010139 if (procs == null) {
10140 return;
10141 }
10142
Dianne Hackborn6447ca32009-04-07 19:50:08 -070010143 final boolean isCheckinRequest = scanArgs(args, "--checkin");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010144 long uptime = SystemClock.uptimeMillis();
10145 long realtime = SystemClock.elapsedRealtime();
Dianne Hackbornb437e092011-08-05 17:50:29 -070010146
10147 if (procs.size() == 1 || isCheckinRequest) {
10148 dumpAll = true;
10149 }
10150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010151 if (isCheckinRequest) {
10152 // short checkin version
10153 pw.println(uptime + "," + realtime);
10154 pw.flush();
10155 } else {
10156 pw.println("Applications Memory Usage (kB):");
10157 pw.println("Uptime: " + uptime + " Realtime: " + realtime);
10158 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010159
Dianne Hackbornb437e092011-08-05 17:50:29 -070010160 String[] innerArgs = new String[args.length-opti];
10161 System.arraycopy(args, opti, innerArgs, 0, args.length-opti);
10162
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010163 ArrayList<MemItem> procMems = new ArrayList<MemItem>();
10164 long nativePss=0, dalvikPss=0, otherPss=0;
10165 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS];
10166
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010167 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length];
10168 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[])
10169 new ArrayList[DUMP_MEM_OOM_LABEL.length];
Dianne Hackbornb437e092011-08-05 17:50:29 -070010170
10171 long totalPss = 0;
10172
Dianne Hackborne17aeb32011-04-07 15:11:57 -070010173 for (int i = procs.size() - 1 ; i >= 0 ; i--) {
10174 ProcessRecord r = procs.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010175 if (r.thread != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010176 if (!isCheckinRequest && dumpAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010177 pw.println("\n** MEMINFO in pid " + r.pid + " [" + r.processName + "] **");
10178 pw.flush();
10179 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010180 Debug.MemoryInfo mi = null;
Dianne Hackbornb437e092011-08-05 17:50:29 -070010181 if (dumpAll) {
10182 try {
10183 mi = r.thread.dumpMemInfo(fd, isCheckinRequest, dumpAll, innerArgs);
10184 } catch (RemoteException e) {
10185 if (!isCheckinRequest) {
10186 pw.println("Got RemoteException!");
10187 pw.flush();
10188 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010189 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010190 } else {
10191 mi = new Debug.MemoryInfo();
10192 Debug.getMemoryInfo(r.pid, mi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010193 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010194
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010195 if (!isCheckinRequest && mi != null) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010196 long myTotalPss = mi.getTotalPss();
10197 totalPss += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010198 MemItem pssItem = new MemItem(r.processName + " (pid " + r.pid + ")",
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010199 r.processName, myTotalPss, 0);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010200 procMems.add(pssItem);
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010201
10202 nativePss += mi.nativePss;
10203 dalvikPss += mi.dalvikPss;
10204 otherPss += mi.otherPss;
10205 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
10206 long mem = mi.getOtherPss(j);
10207 miscPss[j] += mem;
10208 otherPss -= mem;
10209 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010210
10211 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010212 if (r.setAdj <= DUMP_MEM_OOM_ADJ[oomIndex]
10213 || oomIndex == (oomPss.length-1)) {
Dianne Hackbornb437e092011-08-05 17:50:29 -070010214 oomPss[oomIndex] += myTotalPss;
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010215 if (oomProcs[oomIndex] == null) {
10216 oomProcs[oomIndex] = new ArrayList<MemItem>();
10217 }
10218 oomProcs[oomIndex].add(pssItem);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010219 break;
10220 }
10221 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010223 }
10224 }
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010225
10226 if (!isCheckinRequest && procs.size() > 1) {
10227 ArrayList<MemItem> catMems = new ArrayList<MemItem>();
10228
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010229 catMems.add(new MemItem("Native", "Native", nativePss, -1));
10230 catMems.add(new MemItem("Dalvik", "Dalvik", dalvikPss, -2));
10231 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010232 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010233 String label = Debug.MemoryInfo.getOtherLabel(j);
10234 catMems.add(new MemItem(label, label, miscPss[j], j));
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010235 }
10236
Dianne Hackbornb437e092011-08-05 17:50:29 -070010237 ArrayList<MemItem> oomMems = new ArrayList<MemItem>();
10238 for (int j=0; j<oomPss.length; j++) {
10239 if (oomPss[j] != 0) {
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010240 String label = DUMP_MEM_OOM_LABEL[j];
10241 MemItem item = new MemItem(label, label, oomPss[j],
10242 DUMP_MEM_OOM_ADJ[j]);
Dianne Hackborna4bacb82011-08-24 15:12:38 -070010243 item.subitems = oomProcs[j];
10244 oomMems.add(item);
Dianne Hackbornb437e092011-08-05 17:50:29 -070010245 }
10246 }
10247
Dianne Hackborn672342c2011-11-29 11:29:02 -080010248 if (outTag != null || outStack != null) {
10249 if (outTag != null) {
10250 appendMemBucket(outTag, totalPss, "total", false);
10251 }
10252 if (outStack != null) {
10253 appendMemBucket(outStack, totalPss, "total", true);
10254 }
10255 boolean firstLine = true;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010256 for (int i=0; i<oomMems.size(); i++) {
10257 MemItem miCat = oomMems.get(i);
10258 if (miCat.subitems == null || miCat.subitems.size() < 1) {
10259 continue;
10260 }
10261 if (miCat.id < ProcessList.SERVICE_ADJ
10262 || miCat.id == ProcessList.HOME_APP_ADJ
10263 || miCat.id == ProcessList.PREVIOUS_APP_ADJ) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010264 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10265 outTag.append(" / ");
10266 }
10267 if (outStack != null) {
10268 if (miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10269 if (firstLine) {
10270 outStack.append(":");
10271 firstLine = false;
10272 }
10273 outStack.append("\n\t at ");
10274 } else {
10275 outStack.append("$");
10276 }
10277 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010278 for (int j=0; j<miCat.subitems.size(); j++) {
10279 MemItem mi = miCat.subitems.get(j);
10280 if (j > 0) {
Dianne Hackborn672342c2011-11-29 11:29:02 -080010281 if (outTag != null) {
10282 outTag.append(" ");
10283 }
10284 if (outStack != null) {
10285 outStack.append("$");
10286 }
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010287 }
Dianne Hackborn672342c2011-11-29 11:29:02 -080010288 if (outTag != null && miCat.id <= ProcessList.FOREGROUND_APP_ADJ) {
10289 appendMemBucket(outTag, mi.pss, mi.shortLabel, false);
10290 }
10291 if (outStack != null) {
10292 appendMemBucket(outStack, mi.pss, mi.shortLabel, true);
10293 }
10294 }
10295 if (outStack != null && miCat.id >= ProcessList.FOREGROUND_APP_ADJ) {
10296 outStack.append("(");
10297 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) {
10298 if (DUMP_MEM_OOM_ADJ[k] == miCat.id) {
10299 outStack.append(DUMP_MEM_OOM_LABEL[k]);
10300 outStack.append(":");
10301 outStack.append(DUMP_MEM_OOM_ADJ[k]);
10302 }
10303 }
10304 outStack.append(")");
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010305 }
10306 }
10307 }
10308 }
10309
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010310 if (!brief && !oomOnly) {
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010311 pw.println();
10312 pw.println("Total PSS by process:");
10313 dumpMemItems(pw, " ", procMems, true);
10314 pw.println();
10315 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010316 pw.println("Total PSS by OOM adjustment:");
10317 dumpMemItems(pw, " ", oomMems, false);
Dianne Hackborne4d4fbc2011-11-08 11:53:28 -080010318 if (!oomOnly) {
10319 PrintWriter out = categoryPw != null ? categoryPw : pw;
10320 out.println();
10321 out.println("Total PSS by category:");
10322 dumpMemItems(out, " ", catMems, true);
Dianne Hackborn04d6db32011-11-04 20:07:24 -070010323 }
Dianne Hackbornb437e092011-08-05 17:50:29 -070010324 pw.println();
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080010325 pw.print("Total PSS: "); pw.print(totalPss); pw.println(" kB");
Dianne Hackbornd3e677b2012-04-05 14:58:18 -070010326 final int[] SINGLE_LONG_FORMAT = new int[] {
10327 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG
10328 };
10329 long[] longOut = new long[1];
10330 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared",
10331 SINGLE_LONG_FORMAT, null, longOut, null);
10332 long shared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10333 longOut[0] = 0;
10334 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing",
10335 SINGLE_LONG_FORMAT, null, longOut, null);
10336 long sharing = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10337 longOut[0] = 0;
10338 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared",
10339 SINGLE_LONG_FORMAT, null, longOut, null);
10340 long unshared = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10341 longOut[0] = 0;
10342 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile",
10343 SINGLE_LONG_FORMAT, null, longOut, null);
10344 long voltile = longOut[0] * ProcessList.PAGE_SIZE / 1024;
10345 pw.print(" KSM: "); pw.print(sharing); pw.print(" kB saved from shared ");
10346 pw.print(shared); pw.println(" kB");
10347 pw.print(" "); pw.print(unshared); pw.print(" kB unshared; ");
10348 pw.print(voltile); pw.println(" kB volatile");
Dianne Hackborn0e3328f2011-07-17 13:31:17 -070010349 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010350 }
10351
10352 /**
10353 * Searches array of arguments for the specified string
10354 * @param args array of argument strings
10355 * @param value value to search for
10356 * @return true if the value is contained in the array
10357 */
10358 private static boolean scanArgs(String[] args, String value) {
10359 if (args != null) {
10360 for (String arg : args) {
10361 if (value.equals(arg)) {
10362 return true;
10363 }
10364 }
10365 }
10366 return false;
10367 }
10368
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010369 private final boolean removeDyingProviderLocked(ProcessRecord proc,
10370 ContentProviderRecord cpr, boolean always) {
10371 final boolean inLaunching = mLaunchingProviders.contains(cpr);
10372
10373 if (!inLaunching || always) {
10374 synchronized (cpr) {
10375 cpr.launchingApp = null;
10376 cpr.notifyAll();
10377 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010378 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid));
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010379 String names[] = cpr.info.authority.split(";");
10380 for (int j = 0; j < names.length; j++) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010381 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010382 }
10383 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010384
10385 for (int i=0; i<cpr.connections.size(); i++) {
10386 ContentProviderConnection conn = cpr.connections.get(i);
10387 if (conn.waiting) {
10388 // If this connection is waiting for the provider, then we don't
10389 // need to mess with its process unless we are always removing
10390 // or for some reason the provider is not currently launching.
10391 if (inLaunching && !always) {
10392 continue;
10393 }
10394 }
10395 ProcessRecord capp = conn.client;
10396 conn.dead = true;
10397 if (conn.stableCount > 0) {
10398 if (!capp.persistent && capp.thread != null
10399 && capp.pid != 0
10400 && capp.pid != MY_PID) {
10401 Slog.i(TAG, "Kill " + capp.processName
10402 + " (pid " + capp.pid + "): provider " + cpr.info.name
10403 + " in dying process " + (proc != null ? proc.processName : "??"));
10404 EventLog.writeEvent(EventLogTags.AM_KILL, capp.pid,
10405 capp.processName, capp.setAdj, "dying provider "
10406 + cpr.name.toShortString());
10407 Process.killProcessQuiet(capp.pid);
10408 }
10409 } else if (capp.thread != null && conn.provider.provider != null) {
10410 try {
10411 capp.thread.unstableProviderDied(conn.provider.provider.asBinder());
10412 } catch (RemoteException e) {
10413 }
10414 // In the protocol here, we don't expect the client to correctly
10415 // clean up this connection, we'll just remove it.
10416 cpr.connections.remove(i);
10417 conn.client.conProviders.remove(conn);
10418 }
10419 }
10420
10421 if (inLaunching && always) {
10422 mLaunchingProviders.remove(cpr);
10423 }
10424 return inLaunching;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010425 }
10426
10427 /**
10428 * Main code for cleaning up a process when it has gone away. This is
10429 * called both as a result of the process dying, or directly when stopping
10430 * a process when running in single process mode.
10431 */
10432 private final void cleanUpApplicationRecordLocked(ProcessRecord app,
Dianne Hackborn130b0d22011-07-26 22:07:48 -070010433 boolean restarting, boolean allowRestart, int index) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010434 if (index >= 0) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080010435 mLruProcesses.remove(index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010436 }
10437
Dianne Hackborn36124872009-10-08 16:22:03 -070010438 mProcessesToGc.remove(app);
10439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010440 // Dismiss any open dialogs.
10441 if (app.crashDialog != null) {
10442 app.crashDialog.dismiss();
10443 app.crashDialog = null;
10444 }
10445 if (app.anrDialog != null) {
10446 app.anrDialog.dismiss();
10447 app.anrDialog = null;
10448 }
10449 if (app.waitDialog != null) {
10450 app.waitDialog.dismiss();
10451 app.waitDialog = null;
10452 }
10453
10454 app.crashing = false;
10455 app.notResponding = false;
10456
10457 app.resetPackageList();
Dianne Hackborn1b64e0d2011-07-17 15:23:59 -070010458 app.unlinkDeathRecipient();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010459 app.thread = null;
10460 app.forcingToForeground = null;
10461 app.foregroundServices = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010462 app.foregroundActivities = false;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070010463 app.hasShownUi = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070010464 app.hasAboveClient = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010465
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010466 mServices.killServicesLocked(app, allowRestart);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010467
10468 boolean restart = false;
10469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010470 // Remove published content providers.
10471 if (!app.pubProviders.isEmpty()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010472 Iterator<ContentProviderRecord> it = app.pubProviders.values().iterator();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010473 while (it.hasNext()) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010474 ContentProviderRecord cpr = it.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010475
10476 final boolean always = app.bad || !allowRestart;
10477 if (removeDyingProviderLocked(app, cpr, always) || always) {
10478 // We left the provider in the launching list, need to
10479 // restart it.
10480 restart = true;
10481 }
10482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010483 cpr.provider = null;
Dianne Hackborn2a6bcda2011-09-21 15:07:05 -070010484 cpr.proc = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010485 }
10486 app.pubProviders.clear();
10487 }
10488
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010489 // Take care of any launching providers waiting for this process.
10490 if (checkAppInLaunchingProvidersLocked(app, false)) {
10491 restart = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010492 }
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010494 // Unregister from connected content providers.
10495 if (!app.conProviders.isEmpty()) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010496 for (int i=0; i<app.conProviders.size(); i++) {
10497 ContentProviderConnection conn = app.conProviders.get(i);
10498 conn.provider.connections.remove(conn);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010499 }
10500 app.conProviders.clear();
10501 }
10502
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010503 // At this point there may be remaining entries in mLaunchingProviders
10504 // where we were the only one waiting, so they are no longer of use.
10505 // Look for these and clean up if found.
10506 // XXX Commented out for now. Trying to figure out a way to reproduce
10507 // the actual situation to identify what is actually going on.
10508 if (false) {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010509 for (int i=0; i<mLaunchingProviders.size(); i++) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010510 ContentProviderRecord cpr = (ContentProviderRecord)
10511 mLaunchingProviders.get(i);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010512 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070010513 synchronized (cpr) {
10514 cpr.launchingApp = null;
10515 cpr.notifyAll();
10516 }
10517 }
10518 }
10519 }
10520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010521 skipCurrentReceiverLocked(app);
10522
10523 // Unregister any receivers.
10524 if (app.receivers.size() > 0) {
10525 Iterator<ReceiverList> it = app.receivers.iterator();
10526 while (it.hasNext()) {
10527 removeReceiverLocked(it.next());
10528 }
10529 app.receivers.clear();
10530 }
10531
Christopher Tate181fafa2009-05-14 11:12:14 -070010532 // If the app is undergoing backup, tell the backup manager about it
10533 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010534 if (DEBUG_BACKUP) Slog.d(TAG, "App " + mBackupTarget.appInfo + " died during backup");
Christopher Tate181fafa2009-05-14 11:12:14 -070010535 try {
10536 IBackupManager bm = IBackupManager.Stub.asInterface(
10537 ServiceManager.getService(Context.BACKUP_SERVICE));
10538 bm.agentDisconnected(app.info.packageName);
10539 } catch (RemoteException e) {
10540 // can't happen; backup manager is local
10541 }
10542 }
10543
Dianne Hackborna93c2c12012-05-31 15:29:36 -070010544 for (int i = mPendingProcessChanges.size()-1; i>=0; i--) {
10545 ProcessChangeItem item = mPendingProcessChanges.get(i);
10546 if (item.pid == app.pid) {
10547 mPendingProcessChanges.remove(i);
10548 mAvailProcessChanges.add(item);
10549 }
10550 }
Jeff Sharkey287bd832011-05-28 19:36:26 -070010551 mHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070010552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010553 // If the caller is restarting this app, then leave it in its
10554 // current lists and let the caller take care of it.
10555 if (restarting) {
10556 return;
10557 }
10558
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010559 if (!app.persistent || app.isolated) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010560 if (DEBUG_PROCESSES) Slog.v(TAG,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010561 "Removing non-persistent process during cleanup: " + app);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010562 mProcessNames.remove(app.processName, app.uid);
10563 mIsolatedProcesses.remove(app.uid);
Dianne Hackborn860755f2010-06-03 18:47:52 -070010564 if (mHeavyWeightProcess == app) {
10565 mHeavyWeightProcess = null;
10566 mHandler.sendEmptyMessage(CANCEL_HEAVY_NOTIFICATION_MSG);
10567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010568 } else if (!app.removed) {
10569 // This app is persistent, so we need to keep its record around.
10570 // If it is not already on the pending app list, add it there
10571 // and start a new process for it.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010572 if (mPersistentStartingProcesses.indexOf(app) < 0) {
10573 mPersistentStartingProcesses.add(app);
10574 restart = true;
10575 }
10576 }
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070010577 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG,
10578 "Clean-up removing on hold: " + app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010579 mProcessesOnHold.remove(app);
10580
The Android Open Source Project4df24232009-03-05 14:34:35 -080010581 if (app == mHomeProcess) {
10582 mHomeProcess = null;
10583 }
Dianne Hackbornf35fe232011-11-01 19:25:20 -070010584 if (app == mPreviousProcess) {
10585 mPreviousProcess = null;
10586 }
10587
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010588 if (restart && !app.isolated) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010589 // We have components that still need to be running in the
10590 // process, so re-launch it.
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010591 mProcessNames.put(app.processName, app.uid, app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010592 startProcessLocked(app, "restart", app.processName);
10593 } else if (app.pid > 0 && app.pid != MY_PID) {
10594 // Goodbye!
10595 synchronized (mPidsSelfLocked) {
10596 mPidsSelfLocked.remove(app.pid);
10597 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
10598 }
Dianne Hackbornf210d6b2009-04-13 18:42:49 -070010599 app.setPid(0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010600 }
10601 }
10602
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010603 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) {
10604 // Look through the content providers we are waiting to have launched,
10605 // and if any run in this process then either schedule a restart of
10606 // the process or kill the client waiting for it if this process has
10607 // gone bad.
10608 int NL = mLaunchingProviders.size();
10609 boolean restart = false;
10610 for (int i=0; i<NL; i++) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070010611 ContentProviderRecord cpr = mLaunchingProviders.get(i);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010612 if (cpr.launchingApp == app) {
10613 if (!alwaysBad && !app.bad) {
10614 restart = true;
10615 } else {
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070010616 removeDyingProviderLocked(app, cpr, true);
Dianne Hackbornf670ef72009-11-16 13:59:16 -080010617 NL = mLaunchingProviders.size();
10618 }
10619 }
10620 }
10621 return restart;
10622 }
10623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010624 // =========================================================
10625 // SERVICES
10626 // =========================================================
10627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010628 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum,
10629 int flags) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010630 enforceNotIsolatedCaller("getServices");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010631 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010632 return mServices.getRunningServiceInfoLocked(maxNum, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010633 }
10634 }
10635
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010636 public PendingIntent getRunningServiceControlPanel(ComponentName name) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010637 enforceNotIsolatedCaller("getRunningServiceControlPanel");
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010638 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010639 return mServices.getRunningServiceControlPanelLocked(name);
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010640 }
Dianne Hackborndd9b82c2009-09-03 00:18:47 -070010641 }
10642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010643 public ComponentName startService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010644 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010645 enforceNotIsolatedCaller("startService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010646 // Refuse possible leaked file descriptors
10647 if (service != null && service.hasFileDescriptors() == true) {
10648 throw new IllegalArgumentException("File descriptors passed in Intent");
10649 }
10650
Amith Yamasani742a6712011-05-04 14:49:28 -070010651 if (DEBUG_SERVICE)
10652 Slog.v(TAG, "startService: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010653 synchronized(this) {
10654 final int callingPid = Binder.getCallingPid();
10655 final int callingUid = Binder.getCallingUid();
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010656 checkValidCaller(callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010657 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010658 ComponentName res = mServices.startServiceLocked(caller, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010659 resolvedType, callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010660 Binder.restoreCallingIdentity(origId);
10661 return res;
10662 }
10663 }
10664
10665 ComponentName startServiceInPackage(int uid,
10666 Intent service, String resolvedType) {
10667 synchronized(this) {
Amith Yamasani742a6712011-05-04 14:49:28 -070010668 if (DEBUG_SERVICE)
10669 Slog.v(TAG, "startServiceInPackage: " + service + " type=" + resolvedType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010670 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010671 ComponentName res = mServices.startServiceLocked(null, service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010672 resolvedType, -1, uid, UserHandle.getUserId(uid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010673 Binder.restoreCallingIdentity(origId);
10674 return res;
10675 }
10676 }
10677
10678 public int stopService(IApplicationThread caller, Intent service,
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010679 String resolvedType, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010680 enforceNotIsolatedCaller("stopService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010681 // Refuse possible leaked file descriptors
10682 if (service != null && service.hasFileDescriptors() == true) {
10683 throw new IllegalArgumentException("File descriptors passed in Intent");
10684 }
10685
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010686 checkValidCaller(Binder.getCallingUid(), userId);
10687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010688 synchronized(this) {
Dianne Hackborn7767eac2012-08-23 18:25:40 -070010689 return mServices.stopServiceLocked(caller, service, resolvedType, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010690 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010691 }
10692
10693 public IBinder peekService(Intent service, String resolvedType) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010694 enforceNotIsolatedCaller("peekService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010695 // Refuse possible leaked file descriptors
10696 if (service != null && service.hasFileDescriptors() == true) {
10697 throw new IllegalArgumentException("File descriptors passed in Intent");
10698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010699 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010700 return mServices.peekServiceLocked(service, resolvedType);
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 boolean stopServiceToken(ComponentName className, IBinder token,
10705 int startId) {
10706 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010707 return mServices.stopServiceTokenLocked(className, token, startId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010709 }
10710
10711 public void setServiceForeground(ComponentName className, IBinder token,
Dianne Hackbornd8a43f62009-08-17 23:33:56 -070010712 int id, Notification notification, boolean removeNotification) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010713 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010714 mServices.setServiceForegroundLocked(className, token, id, notification,
10715 removeNotification);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010716 }
10717 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010718
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010719 int handleIncomingUserLocked(int callingPid, int callingUid, int userId, boolean allowAll,
10720 boolean requireFull, String name, String callerPackage) {
10721 final int callingUserId = UserHandle.getUserId(callingUid);
10722 if (callingUserId != userId) {
10723 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
10724 if ((requireFull || checkComponentPermission(
10725 android.Manifest.permission.INTERACT_ACROSS_USERS,
10726 callingPid, callingUid, -1, true) != PackageManager.PERMISSION_GRANTED)
10727 && checkComponentPermission(
10728 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10729 callingPid, callingUid, -1, true)
10730 != PackageManager.PERMISSION_GRANTED) {
10731 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
10732 // In this case, they would like to just execute as their
10733 // owner user instead of failing.
10734 userId = callingUserId;
10735 } else {
10736 String msg = "Permission Denial: " + name + " from " + callerPackage
10737 + " asks to run as user " + userId
10738 + " but is calling from user " + UserHandle.getUserId(callingUid)
10739 + "; this requires "
10740 + (requireFull
10741 ? android.Manifest.permission.INTERACT_ACROSS_USERS_FULL
10742 : android.Manifest.permission.INTERACT_ACROSS_USERS);
10743 Slog.w(TAG, msg);
10744 throw new SecurityException(msg);
10745 }
10746 }
10747 }
10748 if (userId == UserHandle.USER_CURRENT
10749 || userId == UserHandle.USER_CURRENT_OR_SELF) {
10750 userId = mCurrentUserId;
10751 }
10752 if (!allowAll && userId < 0) {
10753 throw new IllegalArgumentException(
10754 "Call does not support special user #" + userId);
10755 }
10756 }
10757 return userId;
10758 }
10759
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010760 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo,
10761 String className, int flags) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070010762 boolean result = false;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010763 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010764 if ((flags&ServiceInfo.FLAG_SINGLE_USER) != 0) {
10765 if (ActivityManager.checkUidPermission(
10766 android.Manifest.permission.INTERACT_ACROSS_USERS,
10767 aInfo.uid) != PackageManager.PERMISSION_GRANTED) {
10768 ComponentName comp = new ComponentName(aInfo.packageName, className);
10769 String msg = "Permission Denial: Component " + comp.flattenToShortString()
10770 + " requests FLAG_SINGLE_USER, but app does not hold "
10771 + android.Manifest.permission.INTERACT_ACROSS_USERS;
10772 Slog.w(TAG, msg);
10773 throw new SecurityException(msg);
10774 }
10775 result = true;
10776 }
Amith Yamasania4a54e22012-04-16 15:44:19 -070010777 } else if (componentProcessName == aInfo.packageName) {
10778 result = (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0;
10779 } else if ("system".equals(componentProcessName)) {
10780 result = true;
10781 }
10782 if (DEBUG_MU) {
Dianne Hackborn7d19e022012-08-07 19:12:33 -070010783 Slog.v(TAG, "isSingleton(" + componentProcessName + ", " + aInfo
10784 + ", " + className + ", 0x" + Integer.toHexString(flags) + ") = " + result);
Amith Yamasania4a54e22012-04-16 15:44:19 -070010785 }
10786 return result;
10787 }
10788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010789 public int bindService(IApplicationThread caller, IBinder token,
10790 Intent service, String resolvedType,
Amith Yamasani37ce3a82012-02-06 12:04:42 -080010791 IServiceConnection connection, int flags, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080010792 enforceNotIsolatedCaller("bindService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010793 // Refuse possible leaked file descriptors
10794 if (service != null && service.hasFileDescriptors() == true) {
10795 throw new IllegalArgumentException("File descriptors passed in Intent");
10796 }
10797
10798 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010799 return mServices.bindServiceLocked(caller, token, service, resolvedType,
10800 connection, flags, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010801 }
10802 }
10803
10804 public boolean unbindService(IServiceConnection connection) {
10805 synchronized (this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010806 return mServices.unbindServiceLocked(connection);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010808 }
10809
10810 public void publishService(IBinder token, Intent intent, IBinder service) {
10811 // Refuse possible leaked file descriptors
10812 if (intent != null && intent.hasFileDescriptors() == true) {
10813 throw new IllegalArgumentException("File descriptors passed in Intent");
10814 }
10815
10816 synchronized(this) {
10817 if (!(token instanceof ServiceRecord)) {
10818 throw new IllegalArgumentException("Invalid service token");
10819 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010820 mServices.publishServiceLocked((ServiceRecord)token, intent, service);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010821 }
10822 }
10823
10824 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) {
10825 // Refuse possible leaked file descriptors
10826 if (intent != null && intent.hasFileDescriptors() == true) {
10827 throw new IllegalArgumentException("File descriptors passed in Intent");
10828 }
10829
10830 synchronized(this) {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010831 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010832 }
10833 }
10834
Dianne Hackbornf6f9f2d2009-08-21 16:26:03 -070010835 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010836 synchronized(this) {
10837 if (!(token instanceof ServiceRecord)) {
10838 throw new IllegalArgumentException("Invalid service token");
10839 }
Dianne Hackborn599db5c2012-08-03 19:28:48 -070010840 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070010841 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010842 }
10843
10844 // =========================================================
Christopher Tate181fafa2009-05-14 11:12:14 -070010845 // BACKUP AND RESTORE
10846 // =========================================================
10847
10848 // Cause the target app to be launched if necessary and its backup agent
10849 // instantiated. The backup agent will invoke backupAgentCreated() on the
10850 // activity manager to announce its creation.
10851 public boolean bindBackupAgent(ApplicationInfo app, int backupMode) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010852 if (DEBUG_BACKUP) Slog.v(TAG, "startBackupAgent: app=" + app + " mode=" + backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010853 enforceCallingPermission("android.permission.BACKUP", "startBackupAgent");
10854
10855 synchronized(this) {
10856 // !!! TODO: currently no check here that we're already bound
10857 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
10858 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
10859 synchronized (stats) {
10860 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name);
10861 }
10862
Dianne Hackborne7f97212011-02-24 14:40:20 -080010863 // Backup agent is now in use, its package can't be stopped.
10864 try {
10865 AppGlobals.getPackageManager().setPackageStoppedState(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070010866 app.packageName, false, UserHandle.getUserId(app.uid));
Dianne Hackborne7f97212011-02-24 14:40:20 -080010867 } catch (RemoteException e) {
Dianne Hackborna925cd42011-03-10 13:18:20 -080010868 } catch (IllegalArgumentException e) {
10869 Slog.w(TAG, "Failed trying to unstop package "
10870 + app.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -080010871 }
10872
Christopher Tate181fafa2009-05-14 11:12:14 -070010873 BackupRecord r = new BackupRecord(ss, app, backupMode);
Christopher Tate4a627c72011-04-01 14:43:32 -070010874 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL)
10875 ? new ComponentName(app.packageName, app.backupAgentName)
10876 : new ComponentName("android", "FullBackupAgent");
Christopher Tate181fafa2009-05-14 11:12:14 -070010877 // startProcessLocked() returns existing proc's record if it's already running
10878 ProcessRecord proc = startProcessLocked(app.processName, app,
Dianne Hackborna0c283e2012-02-09 10:47:01 -080010879 false, 0, "backup", hostingName, false, false);
Christopher Tate181fafa2009-05-14 11:12:14 -070010880 if (proc == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010881 Slog.e(TAG, "Unable to start backup agent process " + r);
Christopher Tate181fafa2009-05-14 11:12:14 -070010882 return false;
10883 }
10884
10885 r.app = proc;
10886 mBackupTarget = r;
10887 mBackupAppName = app.packageName;
10888
Christopher Tate6fa95972009-06-05 18:43:55 -070010889 // Try not to kill the process during backup
10890 updateOomAdjLocked(proc);
10891
Christopher Tate181fafa2009-05-14 11:12:14 -070010892 // If the process is already attached, schedule the creation of the backup agent now.
10893 // If it is not yet live, this will be done when it attaches to the framework.
10894 if (proc.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010895 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc already running: " + proc);
Christopher Tate181fafa2009-05-14 11:12:14 -070010896 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010897 proc.thread.scheduleCreateBackupAgent(app,
10898 compatibilityInfoForPackageLocked(app), backupMode);
Christopher Tate181fafa2009-05-14 11:12:14 -070010899 } catch (RemoteException e) {
Christopher Tate436344a2009-09-30 16:17:37 -070010900 // Will time out on the backup manager side
Christopher Tate181fafa2009-05-14 11:12:14 -070010901 }
10902 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010903 if (DEBUG_BACKUP) Slog.v(TAG, "Agent proc not running, waiting for attach");
Christopher Tate181fafa2009-05-14 11:12:14 -070010904 }
10905 // Invariants: at this point, the target app process exists and the application
10906 // is either already running or in the process of coming up. mBackupTarget and
10907 // mBackupAppName describe the app, so that when it binds back to the AM we
10908 // know that it's scheduled for a backup-agent operation.
10909 }
10910
10911 return true;
10912 }
10913
10914 // A backup agent has just come up
10915 public void backupAgentCreated(String agentPackageName, IBinder agent) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010916 if (DEBUG_BACKUP) Slog.v(TAG, "backupAgentCreated: " + agentPackageName
Christopher Tate181fafa2009-05-14 11:12:14 -070010917 + " = " + agent);
10918
10919 synchronized(this) {
10920 if (!agentPackageName.equals(mBackupAppName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010921 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!");
Christopher Tate181fafa2009-05-14 11:12:14 -070010922 return;
10923 }
Dianne Hackborn06740692010-09-22 22:46:21 -070010924 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010925
Dianne Hackborn06740692010-09-22 22:46:21 -070010926 long oldIdent = Binder.clearCallingIdentity();
10927 try {
10928 IBackupManager bm = IBackupManager.Stub.asInterface(
10929 ServiceManager.getService(Context.BACKUP_SERVICE));
10930 bm.agentConnected(agentPackageName, agent);
10931 } catch (RemoteException e) {
10932 // can't happen; the backup manager service is local
10933 } catch (Exception e) {
10934 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: ");
10935 e.printStackTrace();
10936 } finally {
10937 Binder.restoreCallingIdentity(oldIdent);
Christopher Tate181fafa2009-05-14 11:12:14 -070010938 }
10939 }
10940
10941 // done with this agent
10942 public void unbindBackupAgent(ApplicationInfo appInfo) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010943 if (DEBUG_BACKUP) Slog.v(TAG, "unbindBackupAgent: " + appInfo);
Christopher Tate8a27f922009-06-26 11:49:18 -070010944 if (appInfo == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010945 Slog.w(TAG, "unbind backup agent for null app");
Christopher Tate8a27f922009-06-26 11:49:18 -070010946 return;
10947 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010948
10949 synchronized(this) {
Christopher Tate8a27f922009-06-26 11:49:18 -070010950 if (mBackupAppName == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010951 Slog.w(TAG, "Unbinding backup agent with no active backup");
Christopher Tate8a27f922009-06-26 11:49:18 -070010952 return;
10953 }
10954
Christopher Tate181fafa2009-05-14 11:12:14 -070010955 if (!mBackupAppName.equals(appInfo.packageName)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010956 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target");
Christopher Tate181fafa2009-05-14 11:12:14 -070010957 return;
10958 }
10959
Christopher Tate6fa95972009-06-05 18:43:55 -070010960 ProcessRecord proc = mBackupTarget.app;
10961 mBackupTarget = null;
10962 mBackupAppName = null;
10963
10964 // Not backing this app up any more; reset its OOM adjustment
10965 updateOomAdjLocked(proc);
10966
Christopher Tatec7b31e32009-06-10 15:49:30 -070010967 // If the app crashed during backup, 'thread' will be null here
10968 if (proc.thread != null) {
10969 try {
Dianne Hackborne2515ee2011-04-27 18:52:56 -040010970 proc.thread.scheduleDestroyBackupAgent(appInfo,
10971 compatibilityInfoForPackageLocked(appInfo));
Christopher Tatec7b31e32009-06-10 15:49:30 -070010972 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080010973 Slog.e(TAG, "Exception when unbinding backup agent:");
Christopher Tatec7b31e32009-06-10 15:49:30 -070010974 e.printStackTrace();
10975 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010976 }
Christopher Tate181fafa2009-05-14 11:12:14 -070010977 }
10978 }
10979 // =========================================================
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010980 // BROADCASTS
10981 // =========================================================
10982
Josh Bartel7f208742010-02-25 11:01:44 -060010983 private final List getStickiesLocked(String action, IntentFilter filter,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010984 List cur, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010985 final ContentResolver resolver = mContext.getContentResolver();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070010986 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
10987 if (stickies == null) {
10988 return cur;
10989 }
10990 final ArrayList<Intent> list = stickies.get(action);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010991 if (list == null) {
10992 return cur;
10993 }
10994 int N = list.size();
10995 for (int i=0; i<N; i++) {
10996 Intent intent = list.get(i);
10997 if (filter.match(resolver, intent, true, TAG) >= 0) {
10998 if (cur == null) {
10999 cur = new ArrayList<Intent>();
11000 }
11001 cur.add(intent);
11002 }
11003 }
11004 return cur;
11005 }
11006
Christopher Tatef46723b2012-01-26 14:19:24 -080011007 boolean isPendingBroadcastProcessLocked(int pid) {
11008 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid)
11009 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid);
11010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011011
Christopher Tatef46723b2012-01-26 14:19:24 -080011012 void skipPendingBroadcastLocked(int pid) {
11013 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping");
11014 for (BroadcastQueue queue : mBroadcastQueues) {
11015 queue.skipPendingBroadcastLocked(pid);
11016 }
11017 }
11018
11019 // The app just attached; send any pending broadcasts that it should receive
11020 boolean sendPendingBroadcastsLocked(ProcessRecord app) {
11021 boolean didSomething = false;
11022 for (BroadcastQueue queue : mBroadcastQueues) {
11023 didSomething |= queue.sendPendingBroadcastsLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011024 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011025 return didSomething;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011026 }
11027
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011028 public Intent registerReceiver(IApplicationThread caller, String callerPackage,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011029 IIntentReceiver receiver, IntentFilter filter, String permission) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011030 enforceNotIsolatedCaller("registerReceiver");
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011031 int callingUid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011032 synchronized(this) {
11033 ProcessRecord callerApp = null;
11034 if (caller != null) {
11035 callerApp = getRecordForAppLocked(caller);
11036 if (callerApp == null) {
11037 throw new SecurityException(
11038 "Unable to find app for caller " + caller
11039 + " (pid=" + Binder.getCallingPid()
11040 + ") when registering receiver " + receiver);
11041 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011042 if (callerApp.info.uid != Process.SYSTEM_UID &&
11043 !callerApp.pkgList.contains(callerPackage)) {
11044 throw new SecurityException("Given caller package " + callerPackage
11045 + " is not running in process " + callerApp);
11046 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011047 callingUid = callerApp.info.uid;
Dianne Hackborn6c418d52011-06-29 14:05:33 -070011048 } else {
11049 callerPackage = null;
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011050 callingUid = Binder.getCallingUid();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011051 }
11052
11053 List allSticky = null;
11054
11055 // Look for any matching sticky broadcasts...
11056 Iterator actions = filter.actionsIterator();
11057 if (actions != null) {
11058 while (actions.hasNext()) {
11059 String action = (String)actions.next();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011060 allSticky = getStickiesLocked(action, filter, allSticky,
11061 UserHandle.USER_ALL);
11062 allSticky = getStickiesLocked(action, filter, allSticky,
11063 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011064 }
11065 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011066 allSticky = getStickiesLocked(null, filter, allSticky,
11067 UserHandle.USER_ALL);
11068 allSticky = getStickiesLocked(null, filter, allSticky,
11069 UserHandle.getUserId(callingUid));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011070 }
11071
11072 // The first sticky in the list is returned directly back to
11073 // the client.
11074 Intent sticky = allSticky != null ? (Intent)allSticky.get(0) : null;
11075
Joe Onorato8a9b2202010-02-26 18:56:32 -080011076 if (DEBUG_BROADCAST) Slog.v(TAG, "Register receiver " + filter
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011077 + ": " + sticky);
11078
11079 if (receiver == null) {
11080 return sticky;
11081 }
11082
11083 ReceiverList rl
11084 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
11085 if (rl == null) {
11086 rl = new ReceiverList(this, callerApp,
11087 Binder.getCallingPid(),
11088 Binder.getCallingUid(), receiver);
11089 if (rl.app != null) {
11090 rl.app.receivers.add(rl);
11091 } else {
11092 try {
11093 receiver.asBinder().linkToDeath(rl, 0);
11094 } catch (RemoteException e) {
11095 return sticky;
11096 }
11097 rl.linkedToDeath = true;
11098 }
11099 mRegisteredReceivers.put(receiver.asBinder(), rl);
11100 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011101 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage,
11102 permission, callingUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011103 rl.add(bf);
11104 if (!bf.debugCheck()) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011105 Slog.w(TAG, "==> For Dynamic broadast");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011106 }
11107 mReceiverResolver.addFilter(bf);
11108
11109 // Enqueue broadcasts for all existing stickies that match
11110 // this filter.
11111 if (allSticky != null) {
11112 ArrayList receivers = new ArrayList();
11113 receivers.add(bf);
11114
11115 int N = allSticky.size();
11116 for (int i=0; i<N; i++) {
11117 Intent intent = (Intent)allSticky.get(i);
Christopher Tatef46723b2012-01-26 14:19:24 -080011118 BroadcastQueue queue = broadcastQueueForIntent(intent);
11119 BroadcastRecord r = new BroadcastRecord(queue, intent, null,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011120 null, -1, -1, null, receivers, null, 0, null, null,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011121 false, true, true, -1);
Christopher Tatef46723b2012-01-26 14:19:24 -080011122 queue.enqueueParallelBroadcastLocked(r);
11123 queue.scheduleBroadcastsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011124 }
11125 }
11126
11127 return sticky;
11128 }
11129 }
11130
11131 public void unregisterReceiver(IIntentReceiver receiver) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011132 if (DEBUG_BROADCAST) Slog.v(TAG, "Unregister receiver: " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011133
Christopher Tatef46723b2012-01-26 14:19:24 -080011134 final long origId = Binder.clearCallingIdentity();
11135 try {
11136 boolean doTrim = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011137
Christopher Tatef46723b2012-01-26 14:19:24 -080011138 synchronized(this) {
11139 ReceiverList rl
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011140 = (ReceiverList)mRegisteredReceivers.get(receiver.asBinder());
Christopher Tatef46723b2012-01-26 14:19:24 -080011141 if (rl != null) {
11142 if (rl.curBroadcast != null) {
11143 BroadcastRecord r = rl.curBroadcast;
11144 final boolean doNext = finishReceiverLocked(
11145 receiver.asBinder(), r.resultCode, r.resultData,
11146 r.resultExtras, r.resultAbort, true);
11147 if (doNext) {
11148 doTrim = true;
11149 r.queue.processNextBroadcast(false);
11150 }
11151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011152
Christopher Tatef46723b2012-01-26 14:19:24 -080011153 if (rl.app != null) {
11154 rl.app.receivers.remove(rl);
11155 }
11156 removeReceiverLocked(rl);
11157 if (rl.linkedToDeath) {
11158 rl.linkedToDeath = false;
11159 rl.receiver.asBinder().unlinkToDeath(rl, 0);
11160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011161 }
11162 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011163
Christopher Tatef46723b2012-01-26 14:19:24 -080011164 // If we actually concluded any broadcasts, we might now be able
11165 // to trim the recipients' apps from our working set
11166 if (doTrim) {
11167 trimApplications();
11168 return;
11169 }
11170
11171 } finally {
11172 Binder.restoreCallingIdentity(origId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011174 }
11175
11176 void removeReceiverLocked(ReceiverList rl) {
11177 mRegisteredReceivers.remove(rl.receiver.asBinder());
11178 int N = rl.size();
11179 for (int i=0; i<N; i++) {
11180 mReceiverResolver.removeFilter(rl.get(i));
11181 }
11182 }
11183
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011184 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011185 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
11186 ProcessRecord r = mLruProcesses.get(i);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011187 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011188 try {
11189 r.thread.dispatchPackageBroadcast(cmd, packages);
11190 } catch (RemoteException ex) {
11191 }
11192 }
11193 }
11194 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011195
11196 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType,
11197 int[] users) {
11198 List<ResolveInfo> receivers = null;
11199 try {
11200 HashSet<ComponentName> singleUserReceivers = null;
11201 boolean scannedFirstReceivers = false;
11202 for (int user : users) {
11203 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager()
11204 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user);
11205 if (newReceivers != null && newReceivers.size() == 0) {
11206 newReceivers = null;
11207 }
11208 if (receivers == null) {
11209 receivers = newReceivers;
11210 } else if (newReceivers != null) {
11211 // We need to concatenate the additional receivers
11212 // found with what we have do far. This would be easy,
11213 // but we also need to de-dup any receivers that are
11214 // singleUser.
11215 if (!scannedFirstReceivers) {
11216 // Collect any single user receivers we had already retrieved.
11217 scannedFirstReceivers = true;
11218 for (int i=0; i<receivers.size(); i++) {
11219 ResolveInfo ri = receivers.get(i);
11220 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11221 ComponentName cn = new ComponentName(
11222 ri.activityInfo.packageName, ri.activityInfo.name);
11223 if (singleUserReceivers == null) {
11224 singleUserReceivers = new HashSet<ComponentName>();
11225 }
11226 singleUserReceivers.add(cn);
11227 }
11228 }
11229 }
11230 // Add the new results to the existing results, tracking
11231 // and de-dupping single user receivers.
11232 for (int i=0; i<newReceivers.size(); i++) {
11233 ResolveInfo ri = receivers.get(i);
11234 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) {
11235 ComponentName cn = new ComponentName(
11236 ri.activityInfo.packageName, ri.activityInfo.name);
11237 if (singleUserReceivers == null) {
11238 singleUserReceivers = new HashSet<ComponentName>();
11239 }
11240 if (!singleUserReceivers.contains(cn)) {
11241 singleUserReceivers.add(cn);
11242 receivers.add(ri);
11243 }
11244 } else {
11245 receivers.add(ri);
11246 }
11247 }
11248 }
11249 }
11250 } catch (RemoteException ex) {
11251 // pm is in same process, this will never happen.
11252 }
11253 return receivers;
11254 }
11255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011256 private final int broadcastIntentLocked(ProcessRecord callerApp,
11257 String callerPackage, Intent intent, String resolvedType,
11258 IIntentReceiver resultTo, int resultCode, String resultData,
11259 Bundle map, String requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011260 boolean ordered, boolean sticky, int callingPid, int callingUid,
11261 int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011262 intent = new Intent(intent);
11263
Dianne Hackborne7f97212011-02-24 14:40:20 -080011264 // By default broadcasts do not go to stopped apps.
11265 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
11266
Joe Onorato8a9b2202010-02-26 18:56:32 -080011267 if (DEBUG_BROADCAST_LIGHT) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011268 TAG, (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent
Amith Yamasani13593602012-03-22 16:16:17 -070011269 + " ordered=" + ordered + " userid=" + userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011270 if ((resultTo != null) && !ordered) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011271 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011272 }
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011273
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011274 userId = handleIncomingUserLocked(callingPid, callingUid, userId,
11275 true, false, "broadcast", callerPackage);
Dianne Hackbornb4163a62012-08-02 18:31:26 -070011276
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011277 // Make sure that the user who is receiving this broadcast is started
11278 // If not, we will just skip it.
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011279 if (userId != UserHandle.USER_ALL && mStartedUsers.get(userId) == null) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011280 Slog.w(TAG, "Skipping broadcast of " + intent
11281 + ": user " + userId + " is stopped");
11282 return ActivityManager.BROADCAST_SUCCESS;
11283 }
11284
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011285 /*
11286 * Prevent non-system code (defined here to be non-persistent
11287 * processes) from sending protected broadcasts.
11288 */
11289 if (callingUid == Process.SYSTEM_UID || callingUid == Process.PHONE_UID
11290 || callingUid == Process.SHELL_UID || callingUid == Process.BLUETOOTH_UID ||
11291 callingUid == 0) {
11292 // Always okay.
11293 } else if (callerApp == null || !callerApp.persistent) {
11294 try {
11295 if (AppGlobals.getPackageManager().isProtectedBroadcast(
11296 intent.getAction())) {
11297 String msg = "Permission Denial: not allowed to send broadcast "
11298 + intent.getAction() + " from pid="
11299 + callingPid + ", uid=" + callingUid;
11300 Slog.w(TAG, msg);
11301 throw new SecurityException(msg);
11302 }
11303 } catch (RemoteException e) {
11304 Slog.w(TAG, "Remote exception", e);
11305 return ActivityManager.BROADCAST_SUCCESS;
11306 }
11307 }
11308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011309 // Handle special intents: if this broadcast is from the package
11310 // manager about a package being removed, we need to remove all of
11311 // its activities from the history stack.
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011312 final boolean uidRemoved = Intent.ACTION_UID_REMOVED.equals(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011313 intent.getAction());
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011314 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())
11315 || Intent.ACTION_PACKAGE_CHANGED.equals(intent.getAction())
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011316 || Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011317 || uidRemoved) {
11318 if (checkComponentPermission(
11319 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -080011320 callingPid, callingUid, -1, true)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011321 == PackageManager.PERMISSION_GRANTED) {
11322 if (uidRemoved) {
11323 final Bundle intentExtras = intent.getExtras();
11324 final int uid = intentExtras != null
11325 ? intentExtras.getInt(Intent.EXTRA_UID) : -1;
11326 if (uid >= 0) {
11327 BatteryStatsImpl bs = mBatteryStatsService.getActiveStatistics();
11328 synchronized (bs) {
11329 bs.removeUidStatsLocked(uid);
11330 }
11331 }
11332 } else {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011333 // If resources are unavailable just force stop all
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011334 // those packages and flush the attribute cache as well.
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080011335 if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011336 String list[] = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
11337 if (list != null && (list.length > 0)) {
11338 for (String pkg : list) {
Amith Yamasani483f3b02012-03-13 16:08:00 -070011339 forceStopPackageLocked(pkg, -1, false, true, true, false, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011340 }
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011341 sendPackageBroadcastLocked(
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011342 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, userId);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011343 }
11344 } else {
11345 Uri data = intent.getData();
11346 String ssp;
11347 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11348 if (!intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false)) {
11349 forceStopPackageLocked(ssp,
Amith Yamasani483f3b02012-03-13 16:08:00 -070011350 intent.getIntExtra(Intent.EXTRA_UID, -1), false, true, true,
11351 false, userId);
Dianne Hackbornde7faf62009-06-30 13:27:30 -070011352 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011353 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011354 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011355 new String[] {ssp}, userId);
Dianne Hackborn4416c3d2010-05-04 17:22:49 -070011356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011357 }
11358 }
11359 }
11360 } else {
11361 String msg = "Permission Denial: " + intent.getAction()
11362 + " broadcast from " + callerPackage + " (pid=" + callingPid
11363 + ", uid=" + callingUid + ")"
11364 + " requires "
11365 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011366 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011367 throw new SecurityException(msg);
11368 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011369
11370 // Special case for adding a package: by default turn on compatibility
11371 // mode.
11372 } else if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -070011373 Uri data = intent.getData();
11374 String ssp;
11375 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) {
11376 mCompatModePackages.handlePackageAddedLocked(ssp,
11377 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false));
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011379 }
11380
11381 /*
11382 * If this is the time zone changed action, queue up a message that will reset the timezone
11383 * of all currently running processes. This message will get queued up before the broadcast
11384 * happens.
11385 */
11386 if (intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
11387 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE);
11388 }
11389
Robert Greenwalt03595d02010-11-02 14:08:23 -070011390 if (intent.ACTION_CLEAR_DNS_CACHE.equals(intent.getAction())) {
11391 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE);
11392 }
11393
Robert Greenwalt434203a2010-10-11 16:00:27 -070011394 if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
11395 ProxyProperties proxy = intent.getParcelableExtra("proxy");
11396 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY, proxy));
11397 }
11398
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011399 // Add to the sticky list if requested.
11400 if (sticky) {
11401 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY,
11402 callingPid, callingUid)
11403 != PackageManager.PERMISSION_GRANTED) {
11404 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid="
11405 + callingPid + ", uid=" + callingUid
11406 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011407 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011408 throw new SecurityException(msg);
11409 }
11410 if (requiredPermission != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011411 Slog.w(TAG, "Can't broadcast sticky intent " + intent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011412 + " and enforce permission " + requiredPermission);
Dianne Hackborna4972e92012-03-14 10:38:05 -070011413 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011414 }
11415 if (intent.getComponent() != null) {
11416 throw new SecurityException(
11417 "Sticky broadcasts can't target a specific component");
11418 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011419 // We use userId directly here, since the "all" target is maintained
11420 // as a separate set of sticky broadcasts.
11421 if (userId != UserHandle.USER_ALL) {
11422 // But first, if this is not a broadcast to all users, then
11423 // make sure it doesn't conflict with an existing broadcast to
11424 // all users.
11425 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(
11426 UserHandle.USER_ALL);
11427 if (stickies != null) {
11428 ArrayList<Intent> list = stickies.get(intent.getAction());
11429 if (list != null) {
11430 int N = list.size();
11431 int i;
11432 for (i=0; i<N; i++) {
11433 if (intent.filterEquals(list.get(i))) {
11434 throw new IllegalArgumentException(
11435 "Sticky broadcast " + intent + " for user "
11436 + userId + " conflicts with existing global broadcast");
11437 }
11438 }
11439 }
11440 }
11441 }
11442 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11443 if (stickies == null) {
11444 stickies = new HashMap<String, ArrayList<Intent>>();
11445 mStickyBroadcasts.put(userId, stickies);
11446 }
11447 ArrayList<Intent> list = stickies.get(intent.getAction());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011448 if (list == null) {
11449 list = new ArrayList<Intent>();
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011450 stickies.put(intent.getAction(), list);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011451 }
11452 int N = list.size();
11453 int i;
11454 for (i=0; i<N; i++) {
11455 if (intent.filterEquals(list.get(i))) {
11456 // This sticky already exists, replace it.
11457 list.set(i, new Intent(intent));
11458 break;
11459 }
11460 }
11461 if (i >= N) {
11462 list.add(new Intent(intent));
11463 }
11464 }
11465
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011466 int[] users;
11467 if (userId == UserHandle.USER_ALL) {
11468 // Caller wants broadcast to go to all started users.
11469 users = new int[mStartedUsers.size()];
11470 for (int i=0; i<mStartedUsers.size(); i++) {
11471 users[i] = mStartedUsers.keyAt(i);
11472 }
11473 } else {
11474 // Caller wants broadcast to go to one specific user.
11475 users = new int[] {userId};
11476 }
11477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011478 // Figure out who all will receive this broadcast.
11479 List receivers = null;
11480 List<BroadcastFilter> registeredReceivers = null;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011481 // Need to resolve the intent to interested receivers...
11482 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY)
11483 == 0) {
11484 receivers = collectReceiverComponents(intent, resolvedType, users);
11485 }
11486 if (intent.getComponent() == null) {
11487 registeredReceivers = mReceiverResolver.queryIntent(intent,
11488 resolvedType, false, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011489 }
11490
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011491 final boolean replacePending =
11492 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0;
11493
Joe Onorato8a9b2202010-02-26 18:56:32 -080011494 if (DEBUG_BROADCAST) Slog.v(TAG, "Enqueing broadcast: " + intent.getAction()
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011495 + " replacePending=" + replacePending);
11496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011497 int NR = registeredReceivers != null ? registeredReceivers.size() : 0;
11498 if (!ordered && NR > 0) {
11499 // If we are not serializing this broadcast, then send the
11500 // registered receivers separately so they don't wait for the
11501 // components to be launched.
Christopher Tatef46723b2012-01-26 14:19:24 -080011502 final BroadcastQueue queue = broadcastQueueForIntent(intent);
11503 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011504 callerPackage, callingPid, callingUid, requiredPermission,
11505 registeredReceivers, resultTo, resultCode, resultData, map,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011506 ordered, sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011507 if (DEBUG_BROADCAST) Slog.v(
Christopher Tatef46723b2012-01-26 14:19:24 -080011508 TAG, "Enqueueing parallel broadcast " + r);
11509 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011510 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011511 queue.enqueueParallelBroadcastLocked(r);
11512 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011514 registeredReceivers = null;
11515 NR = 0;
11516 }
11517
11518 // Merge into one list.
11519 int ir = 0;
11520 if (receivers != null) {
11521 // A special case for PACKAGE_ADDED: do not allow the package
11522 // being added to see this broadcast. This prevents them from
11523 // using this as a back door to get run as soon as they are
11524 // installed. Maybe in the future we want to have a special install
11525 // broadcast or such for apps, but we'd like to deliberately make
11526 // this decision.
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011527 String skipPackages[] = null;
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011528 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())
11529 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction())
11530 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011531 Uri data = intent.getData();
11532 if (data != null) {
11533 String pkgName = data.getSchemeSpecificPart();
11534 if (pkgName != null) {
11535 skipPackages = new String[] { pkgName };
11536 }
11537 }
Dianne Hackborn0f1de9a2011-05-11 17:34:49 -070011538 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011539 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
The Android Open Source Project10592532009-03-18 17:39:46 -070011540 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080011541 if (skipPackages != null && (skipPackages.length > 0)) {
11542 for (String skipPackage : skipPackages) {
11543 if (skipPackage != null) {
11544 int NT = receivers.size();
11545 for (int it=0; it<NT; it++) {
11546 ResolveInfo curt = (ResolveInfo)receivers.get(it);
11547 if (curt.activityInfo.packageName.equals(skipPackage)) {
11548 receivers.remove(it);
11549 it--;
11550 NT--;
11551 }
11552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011553 }
11554 }
11555 }
11556
11557 int NT = receivers != null ? receivers.size() : 0;
11558 int it = 0;
11559 ResolveInfo curt = null;
11560 BroadcastFilter curr = null;
11561 while (it < NT && ir < NR) {
11562 if (curt == null) {
11563 curt = (ResolveInfo)receivers.get(it);
11564 }
11565 if (curr == null) {
11566 curr = registeredReceivers.get(ir);
11567 }
11568 if (curr.getPriority() >= curt.priority) {
11569 // Insert this broadcast record into the final list.
11570 receivers.add(it, curr);
11571 ir++;
11572 curr = null;
11573 it++;
11574 NT++;
11575 } else {
11576 // Skip to the next ResolveInfo in the final list.
11577 it++;
11578 curt = null;
11579 }
11580 }
11581 }
11582 while (ir < NR) {
11583 if (receivers == null) {
11584 receivers = new ArrayList();
11585 }
11586 receivers.add(registeredReceivers.get(ir));
11587 ir++;
11588 }
11589
11590 if ((receivers != null && receivers.size() > 0)
11591 || resultTo != null) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011592 BroadcastQueue queue = broadcastQueueForIntent(intent);
11593 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011594 callerPackage, callingPid, callingUid, requiredPermission,
Dianne Hackborn12527f92009-11-11 17:39:50 -080011595 receivers, resultTo, resultCode, resultData, map, ordered,
Amith Yamasani8bf06ed2012-08-27 19:30:30 -070011596 sticky, false, userId);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011597 if (DEBUG_BROADCAST) Slog.v(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011598 TAG, "Enqueueing ordered broadcast " + r
Christopher Tatef46723b2012-01-26 14:19:24 -080011599 + ": prev had " + queue.mOrderedBroadcasts.size());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011600 if (DEBUG_BROADCAST) {
11601 int seq = r.intent.getIntExtra("seq", -1);
Joe Onorato8a9b2202010-02-26 18:56:32 -080011602 Slog.i(TAG, "Enqueueing broadcast " + r.intent.getAction() + " seq=" + seq);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011603 }
Christopher Tatef46723b2012-01-26 14:19:24 -080011604 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011605 if (!replaced) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011606 queue.enqueueOrderedBroadcastLocked(r);
11607 queue.scheduleBroadcastsLocked();
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080011608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011609 }
11610
Dianne Hackborna4972e92012-03-14 10:38:05 -070011611 return ActivityManager.BROADCAST_SUCCESS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011612 }
11613
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011614 final Intent verifyBroadcastLocked(Intent intent) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011615 // Refuse possible leaked file descriptors
11616 if (intent != null && intent.hasFileDescriptors() == true) {
11617 throw new IllegalArgumentException("File descriptors passed in Intent");
11618 }
11619
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011620 int flags = intent.getFlags();
11621
11622 if (!mProcessesReady) {
11623 // if the caller really truly claims to know what they're doing, go
11624 // ahead and allow the broadcast without launching any receivers
11625 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) {
11626 intent = new Intent(intent);
11627 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
11628 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) {
11629 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent
11630 + " before boot completion");
11631 throw new IllegalStateException("Cannot broadcast before boot completed");
11632 }
11633 }
11634
11635 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) {
11636 throw new IllegalArgumentException(
11637 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here");
11638 }
11639
11640 return intent;
11641 }
11642
11643 public final int broadcastIntent(IApplicationThread caller,
11644 Intent intent, String resolvedType, IIntentReceiver resultTo,
11645 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011646 String requiredPermission, boolean serialized, boolean sticky, int userId) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011647 enforceNotIsolatedCaller("broadcastIntent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011648 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011649 intent = verifyBroadcastLocked(intent);
Dianne Hackborn9acc0302009-08-25 00:27:12 -070011650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011651 final ProcessRecord callerApp = getRecordForAppLocked(caller);
11652 final int callingPid = Binder.getCallingPid();
11653 final int callingUid = Binder.getCallingUid();
11654 final long origId = Binder.clearCallingIdentity();
11655 int res = broadcastIntentLocked(callerApp,
11656 callerApp != null ? callerApp.info.packageName : null,
11657 intent, resolvedType, resultTo,
Amith Yamasani742a6712011-05-04 14:49:28 -070011658 resultCode, resultData, map, requiredPermission, serialized, sticky,
11659 callingPid, callingUid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011660 Binder.restoreCallingIdentity(origId);
11661 return res;
11662 }
11663 }
11664
11665 int broadcastIntentInPackage(String packageName, int uid,
11666 Intent intent, String resolvedType, IIntentReceiver resultTo,
11667 int resultCode, String resultData, Bundle map,
Amith Yamasani742a6712011-05-04 14:49:28 -070011668 String requiredPermission, boolean serialized, boolean sticky, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011669 synchronized(this) {
Dianne Hackborn8891fdc2010-09-20 20:44:46 -070011670 intent = verifyBroadcastLocked(intent);
11671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011672 final long origId = Binder.clearCallingIdentity();
11673 int res = broadcastIntentLocked(null, packageName, intent, resolvedType,
11674 resultTo, resultCode, resultData, map, requiredPermission,
Amith Yamasani742a6712011-05-04 14:49:28 -070011675 serialized, sticky, -1, uid, userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011676 Binder.restoreCallingIdentity(origId);
11677 return res;
11678 }
11679 }
11680
Amith Yamasani742a6712011-05-04 14:49:28 -070011681 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011682 // Refuse possible leaked file descriptors
11683 if (intent != null && intent.hasFileDescriptors() == true) {
11684 throw new IllegalArgumentException("File descriptors passed in Intent");
11685 }
11686
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011687 userId = handleIncomingUserLocked(Binder.getCallingPid(),
11688 Binder.getCallingUid(), userId, true, false, "removeStickyBroadcast", null);
11689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011690 synchronized(this) {
11691 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY)
11692 != PackageManager.PERMISSION_GRANTED) {
11693 String msg = "Permission Denial: unbroadcastIntent() from pid="
11694 + Binder.getCallingPid()
11695 + ", uid=" + Binder.getCallingUid()
11696 + " requires " + android.Manifest.permission.BROADCAST_STICKY;
Joe Onorato8a9b2202010-02-26 18:56:32 -080011697 Slog.w(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011698 throw new SecurityException(msg);
11699 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011700 HashMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId);
11701 if (stickies != null) {
11702 ArrayList<Intent> list = stickies.get(intent.getAction());
11703 if (list != null) {
11704 int N = list.size();
11705 int i;
11706 for (i=0; i<N; i++) {
11707 if (intent.filterEquals(list.get(i))) {
11708 list.remove(i);
11709 break;
11710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011711 }
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070011712 if (list.size() <= 0) {
11713 stickies.remove(intent.getAction());
11714 }
11715 }
11716 if (stickies.size() <= 0) {
11717 mStickyBroadcasts.remove(userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011718 }
11719 }
11720 }
11721 }
11722
11723 private final boolean finishReceiverLocked(IBinder receiver, int resultCode,
11724 String resultData, Bundle resultExtras, boolean resultAbort,
11725 boolean explicit) {
Christopher Tatef46723b2012-01-26 14:19:24 -080011726 final BroadcastRecord r = broadcastRecordForReceiverLocked(receiver);
11727 if (r == null) {
11728 Slog.w(TAG, "finishReceiver called but not found on queue");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011729 return false;
11730 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011731
Christopher Tatef46723b2012-01-26 14:19:24 -080011732 return r.queue.finishReceiverLocked(r, resultCode, resultData, resultExtras, resultAbort,
11733 explicit);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011734 }
11735
11736 public void finishReceiver(IBinder who, int resultCode, String resultData,
11737 Bundle resultExtras, boolean resultAbort) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011738 if (DEBUG_BROADCAST) Slog.v(TAG, "Finish receiver: " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011739
11740 // Refuse possible leaked file descriptors
11741 if (resultExtras != null && resultExtras.hasFileDescriptors()) {
11742 throw new IllegalArgumentException("File descriptors passed in Bundle");
11743 }
11744
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011745 final long origId = Binder.clearCallingIdentity();
Christopher Tatef46723b2012-01-26 14:19:24 -080011746 try {
11747 boolean doNext = false;
11748 BroadcastRecord r = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011749
Christopher Tatef46723b2012-01-26 14:19:24 -080011750 synchronized(this) {
11751 r = broadcastRecordForReceiverLocked(who);
11752 if (r != null) {
11753 doNext = r.queue.finishReceiverLocked(r, resultCode,
11754 resultData, resultExtras, resultAbort, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011756 }
Jeff Brown4d94a762010-09-23 11:33:28 -070011757
Christopher Tatef46723b2012-01-26 14:19:24 -080011758 if (doNext) {
11759 r.queue.processNextBroadcast(false);
11760 }
11761 trimApplications();
11762 } finally {
11763 Binder.restoreCallingIdentity(origId);
Dianne Hackbornad5499d2010-03-29 18:08:45 -070011764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011767 // =========================================================
11768 // INSTRUMENTATION
11769 // =========================================================
11770
11771 public boolean startInstrumentation(ComponentName className,
11772 String profileFile, int flags, Bundle arguments,
11773 IInstrumentationWatcher watcher) {
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011774 enforceNotIsolatedCaller("startInstrumentation");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011775 // Refuse possible leaked file descriptors
11776 if (arguments != null && arguments.hasFileDescriptors()) {
11777 throw new IllegalArgumentException("File descriptors passed in Bundle");
11778 }
11779
11780 synchronized(this) {
11781 InstrumentationInfo ii = null;
11782 ApplicationInfo ai = null;
11783 try {
11784 ii = mContext.getPackageManager().getInstrumentationInfo(
Dianne Hackborn1655be42009-05-08 14:29:01 -070011785 className, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011786 ai = mContext.getPackageManager().getApplicationInfo(
Amith Yamasani483f3b02012-03-13 16:08:00 -070011787 ii.targetPackage, STOCK_PM_FLAGS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011788 } catch (PackageManager.NameNotFoundException e) {
11789 }
11790 if (ii == null) {
11791 reportStartInstrumentationFailure(watcher, className,
11792 "Unable to find instrumentation info for: " + className);
11793 return false;
11794 }
11795 if (ai == null) {
11796 reportStartInstrumentationFailure(watcher, className,
11797 "Unable to find instrumentation target package: " + ii.targetPackage);
11798 return false;
11799 }
11800
11801 int match = mContext.getPackageManager().checkSignatures(
11802 ii.targetPackage, ii.packageName);
11803 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) {
11804 String msg = "Permission Denial: starting instrumentation "
11805 + className + " from pid="
11806 + Binder.getCallingPid()
11807 + ", uid=" + Binder.getCallingPid()
11808 + " not allowed because package " + ii.packageName
11809 + " does not have a signature matching the target "
11810 + ii.targetPackage;
11811 reportStartInstrumentationFailure(watcher, className, msg);
11812 throw new SecurityException(msg);
11813 }
11814
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011815 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011816 final long origId = Binder.clearCallingIdentity();
Christopher Tate3dacd842011-08-19 14:56:15 -070011817 // Instrumentation can kill and relaunch even persistent processes
Amith Yamasani483f3b02012-03-13 16:08:00 -070011818 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, userId);
Dianne Hackborna0c283e2012-02-09 10:47:01 -080011819 ProcessRecord app = addAppLocked(ai, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011820 app.instrumentationClass = className;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011821 app.instrumentationInfo = ai;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011822 app.instrumentationProfileFile = profileFile;
11823 app.instrumentationArguments = arguments;
11824 app.instrumentationWatcher = watcher;
11825 app.instrumentationResultClass = className;
11826 Binder.restoreCallingIdentity(origId);
11827 }
11828
11829 return true;
11830 }
11831
11832 /**
11833 * Report errors that occur while attempting to start Instrumentation. Always writes the
11834 * error to the logs, but if somebody is watching, send the report there too. This enables
11835 * the "am" command to report errors with more information.
11836 *
11837 * @param watcher The IInstrumentationWatcher. Null if there isn't one.
11838 * @param cn The component name of the instrumentation.
11839 * @param report The error report.
11840 */
11841 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher,
11842 ComponentName cn, String report) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011843 Slog.w(TAG, report);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011844 try {
11845 if (watcher != null) {
11846 Bundle results = new Bundle();
11847 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService");
11848 results.putString("Error", report);
11849 watcher.instrumentationStatus(cn, -1, results);
11850 }
11851 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011852 Slog.w(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011853 }
11854 }
11855
11856 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) {
11857 if (app.instrumentationWatcher != null) {
11858 try {
11859 // NOTE: IInstrumentationWatcher *must* be oneway here
11860 app.instrumentationWatcher.instrumentationFinished(
11861 app.instrumentationClass,
11862 resultCode,
11863 results);
11864 } catch (RemoteException e) {
11865 }
11866 }
11867 app.instrumentationWatcher = null;
11868 app.instrumentationClass = null;
Dianne Hackborn1655be42009-05-08 14:29:01 -070011869 app.instrumentationInfo = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011870 app.instrumentationProfileFile = null;
11871 app.instrumentationArguments = null;
11872
Dianne Hackborn80a4af22012-08-27 19:18:31 -070011873 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, app.userId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011874 }
11875
11876 public void finishInstrumentation(IApplicationThread target,
11877 int resultCode, Bundle results) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070011878 int userId = UserHandle.getCallingUserId();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011879 // Refuse possible leaked file descriptors
11880 if (results != null && results.hasFileDescriptors()) {
11881 throw new IllegalArgumentException("File descriptors passed in Intent");
11882 }
11883
11884 synchronized(this) {
11885 ProcessRecord app = getRecordForAppLocked(target);
11886 if (app == null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011887 Slog.w(TAG, "finishInstrumentation: no app for " + target);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011888 return;
11889 }
11890 final long origId = Binder.clearCallingIdentity();
11891 finishInstrumentationLocked(app, resultCode, results);
11892 Binder.restoreCallingIdentity(origId);
11893 }
11894 }
11895
11896 // =========================================================
11897 // CONFIGURATION
11898 // =========================================================
11899
11900 public ConfigurationInfo getDeviceConfigurationInfo() {
11901 ConfigurationInfo config = new ConfigurationInfo();
11902 synchronized (this) {
11903 config.reqTouchScreen = mConfiguration.touchscreen;
11904 config.reqKeyboardType = mConfiguration.keyboard;
11905 config.reqNavigation = mConfiguration.navigation;
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011906 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD
11907 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011908 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV;
11909 }
Dianne Hackbornfae76f52009-07-16 13:41:23 -070011910 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED
11911 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011912 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD;
11913 }
Jack Palevichb90d28c2009-07-22 15:35:24 -070011914 config.reqGlEsVersion = GL_ES_VERSION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011915 }
11916 return config;
11917 }
11918
11919 public Configuration getConfiguration() {
11920 Configuration ci;
11921 synchronized(this) {
11922 ci = new Configuration(mConfiguration);
11923 }
11924 return ci;
11925 }
11926
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011927 public void updatePersistentConfiguration(Configuration values) {
11928 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11929 "updateConfiguration()");
11930 enforceCallingPermission(android.Manifest.permission.WRITE_SETTINGS,
11931 "updateConfiguration()");
11932 if (values == null) {
11933 throw new NullPointerException("Configuration must not be null");
11934 }
11935
11936 synchronized(this) {
11937 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn813075a62011-11-14 17:45:19 -080011938 updateConfigurationLocked(values, null, true, false);
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011939 Binder.restoreCallingIdentity(origId);
11940 }
11941 }
11942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011943 public void updateConfiguration(Configuration values) {
11944 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
11945 "updateConfiguration()");
11946
11947 synchronized(this) {
11948 if (values == null && mWindowManager != null) {
11949 // sentinel: fetch the current configuration from the window manager
11950 values = mWindowManager.computeNewConfiguration();
11951 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070011952
11953 if (mWindowManager != null) {
11954 mProcessList.applyDisplaySize(mWindowManager);
11955 }
11956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011957 final long origId = Binder.clearCallingIdentity();
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011958 if (values != null) {
11959 Settings.System.clearConfiguration(values);
11960 }
Dianne Hackborn813075a62011-11-14 17:45:19 -080011961 updateConfigurationLocked(values, null, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011962 Binder.restoreCallingIdentity(origId);
11963 }
11964 }
11965
11966 /**
11967 * Do either or both things: (1) change the current configuration, and (2)
11968 * make sure the given activity is running with the (now) current
11969 * configuration. Returns true if the activity has been left running, or
11970 * false if <var>starting</var> is being destroyed to match the new
11971 * configuration.
Dianne Hackborn31ca8542011-07-19 14:58:28 -070011972 * @param persistent TODO
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011973 */
Dianne Hackborna573f6a2012-02-09 16:12:18 -080011974 boolean updateConfigurationLocked(Configuration values,
Dianne Hackborn813075a62011-11-14 17:45:19 -080011975 ActivityRecord starting, boolean persistent, boolean initLocale) {
Mike Lockwood3a74bd32011-08-12 13:55:22 -070011976 // do nothing if we are headless
11977 if (mHeadless) return true;
11978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011979 int changes = 0;
11980
11981 boolean kept = true;
11982
11983 if (values != null) {
11984 Configuration newConfig = new Configuration(mConfiguration);
11985 changes = newConfig.updateFrom(values);
11986 if (changes != 0) {
Dianne Hackborndc6b6352009-09-30 14:20:09 -070011987 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080011988 Slog.i(TAG, "Updating configuration to: " + values);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011989 }
11990
Doug Zongker2bec3d42009-12-04 12:52:44 -080011991 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011992
Dianne Hackborn813075a62011-11-14 17:45:19 -080011993 if (values.locale != null && !initLocale) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080011994 saveLocaleLocked(values.locale,
11995 !values.locale.equals(mConfiguration.locale),
11996 values.userSetLocale);
11997 }
11998
Dianne Hackborne36d6e22010-02-17 19:46:25 -080011999 mConfigurationSeq++;
12000 if (mConfigurationSeq <= 0) {
12001 mConfigurationSeq = 1;
12002 }
12003 newConfig.seq = mConfigurationSeq;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012004 mConfiguration = newConfig;
Joe Onorato8a9b2202010-02-26 18:56:32 -080012005 Slog.i(TAG, "Config changed: " + newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012006
12007 final Configuration configCopy = new Configuration(mConfiguration);
Joe Onorato54a4a412011-11-02 20:50:08 -070012008
12009 // TODO: If our config changes, should we auto dismiss any currently
12010 // showing dialogs?
12011 mShowDialogs = shouldShowDialogs(newConfig);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012012
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012013 AttributeCache ac = AttributeCache.instance();
12014 if (ac != null) {
Dianne Hackborn813075a62011-11-14 17:45:19 -080012015 ac.updateConfiguration(configCopy);
Dianne Hackborn826d17c2009-11-12 12:55:51 -080012016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012017
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012018 // Make sure all resources in our process are updated
12019 // right now, so that anyone who is going to retrieve
12020 // resource values after we return will be sure to get
12021 // the new ones. This is especially important during
12022 // boot, where the first config change needs to guarantee
12023 // all resources have that config before following boot
12024 // code is executed.
Dianne Hackborn813075a62011-11-14 17:45:19 -080012025 mSystemThread.applyConfigurationToResources(configCopy);
Dianne Hackborn2f0b1752011-05-31 17:59:49 -070012026
Dianne Hackborn31ca8542011-07-19 14:58:28 -070012027 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) {
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012028 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012029 msg.obj = new Configuration(configCopy);
Dianne Hackbornb8b11a02010-03-10 15:53:11 -080012030 mHandler.sendMessage(msg);
12031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012032
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012033 for (int i=mLruProcesses.size()-1; i>=0; i--) {
12034 ProcessRecord app = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012035 try {
12036 if (app.thread != null) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012037 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending to proc "
Dianne Hackborndc6b6352009-09-30 14:20:09 -070012038 + app.processName + " new config " + mConfiguration);
Dianne Hackborn813075a62011-11-14 17:45:19 -080012039 app.thread.scheduleConfigurationChanged(configCopy);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012040 }
12041 } catch (Exception e) {
12042 }
12043 }
12044 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -080012045 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
12046 | Intent.FLAG_RECEIVER_REPLACE_PENDING);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012047 broadcastIntentLocked(null, null, intent, null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012048 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012049 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) {
12050 broadcastIntentLocked(null, null,
12051 new Intent(Intent.ACTION_LOCALE_CHANGED),
12052 null, null, 0, null, null,
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070012053 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
Dianne Hackborn362d5b92009-11-11 18:04:39 -080012054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012055 }
12056 }
12057
12058 if (changes != 0 && starting == null) {
12059 // If the configuration changed, and the caller is not already
12060 // in the process of starting an activity, then find the top
12061 // activity to check if its configuration needs to change.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012062 starting = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012063 }
12064
12065 if (starting != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012066 kept = mMainStack.ensureActivityConfigurationLocked(starting, changes);
Dianne Hackborn5f4d6432010-12-21 20:40:11 -080012067 // And we need to make sure at this point that all other activities
12068 // are made visible with the correct configuration.
12069 mMainStack.ensureActivitiesVisibleLocked(starting, changes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012070 }
12071
Dianne Hackborne36d6e22010-02-17 19:46:25 -080012072 if (values != null && mWindowManager != null) {
12073 mWindowManager.setNewConfiguration(mConfiguration);
12074 }
12075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012076 return kept;
12077 }
Joe Onorato54a4a412011-11-02 20:50:08 -070012078
12079 /**
12080 * Decide based on the configuration whether we should shouw the ANR,
12081 * crash, etc dialogs. The idea is that if there is no affordnace to
12082 * press the on-screen buttons, we shouldn't show the dialog.
12083 *
12084 * A thought: SystemUI might also want to get told about this, the Power
12085 * dialog / global actions also might want different behaviors.
12086 */
12087 private static final boolean shouldShowDialogs(Configuration config) {
12088 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS
12089 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH);
12090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012091
12092 /**
12093 * Save the locale. You must be inside a synchronized (this) block.
12094 */
12095 private void saveLocaleLocked(Locale l, boolean isDiff, boolean isPersist) {
12096 if(isDiff) {
12097 SystemProperties.set("user.language", l.getLanguage());
12098 SystemProperties.set("user.region", l.getCountry());
12099 }
12100
12101 if(isPersist) {
12102 SystemProperties.set("persist.sys.language", l.getLanguage());
12103 SystemProperties.set("persist.sys.country", l.getCountry());
12104 SystemProperties.set("persist.sys.localevar", l.getVariant());
12105 }
12106 }
12107
Adam Powelldd8fab22012-03-22 17:47:27 -070012108 @Override
12109 public boolean targetTaskAffinityMatchesActivity(IBinder token, String destAffinity) {
12110 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012111 return srec != null && srec.task.affinity != null &&
12112 srec.task.affinity.equals(destAffinity);
Adam Powelldd8fab22012-03-22 17:47:27 -070012113 }
12114
12115 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode,
12116 Intent resultData) {
12117 ComponentName dest = destIntent.getComponent();
12118
12119 synchronized (this) {
12120 ActivityRecord srec = ActivityRecord.forToken(token);
Adam Powellb71a5bc2012-04-24 14:20:57 -070012121 if (srec == null) {
12122 return false;
12123 }
Adam Powelldd8fab22012-03-22 17:47:27 -070012124 ArrayList<ActivityRecord> history = srec.stack.mHistory;
12125 final int start = history.indexOf(srec);
12126 if (start < 0) {
12127 // Current activity is not in history stack; do nothing.
12128 return false;
12129 }
12130 int finishTo = start - 1;
12131 ActivityRecord parent = null;
12132 boolean foundParentInTask = false;
12133 if (dest != null) {
12134 TaskRecord tr = srec.task;
12135 for (int i = start - 1; i >= 0; i--) {
12136 ActivityRecord r = history.get(i);
12137 if (tr != r.task) {
12138 // Couldn't find parent in the same task; stop at the one above this.
12139 // (Root of current task; in-app "home" behavior)
12140 // Always at least finish the current activity.
12141 finishTo = Math.min(start - 1, i + 1);
12142 parent = history.get(finishTo);
12143 break;
12144 } else if (r.info.packageName.equals(dest.getPackageName()) &&
12145 r.info.name.equals(dest.getClassName())) {
12146 finishTo = i;
12147 parent = r;
12148 foundParentInTask = true;
12149 break;
12150 }
12151 }
12152 }
12153
12154 if (mController != null) {
12155 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0);
12156 if (next != null) {
12157 // ask watcher if this is allowed
12158 boolean resumeOK = true;
12159 try {
12160 resumeOK = mController.activityResuming(next.packageName);
12161 } catch (RemoteException e) {
12162 mController = null;
12163 }
12164
12165 if (!resumeOK) {
12166 return false;
12167 }
12168 }
12169 }
12170 final long origId = Binder.clearCallingIdentity();
12171 for (int i = start; i > finishTo; i--) {
12172 ActivityRecord r = history.get(i);
12173 mMainStack.requestFinishActivityLocked(r.appToken, resultCode, resultData,
12174 "navigate-up");
12175 // Only return the supplied result for the first activity finished
12176 resultCode = Activity.RESULT_CANCELED;
12177 resultData = null;
12178 }
12179
12180 if (parent != null && foundParentInTask) {
12181 final int parentLaunchMode = parent.info.launchMode;
12182 final int destIntentFlags = destIntent.getFlags();
12183 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
12184 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
12185 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
12186 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
Adam Powell69de7e12012-05-07 18:42:24 -070012187 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
Adam Powelldd8fab22012-03-22 17:47:27 -070012188 } else {
12189 try {
12190 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070012191 destIntent.getComponent(), 0, UserHandle.getCallingUserId());
Adam Powelldd8fab22012-03-22 17:47:27 -070012192 int res = mMainStack.startActivityLocked(srec.app.thread, destIntent,
12193 null, aInfo, parent.appToken, null,
12194 0, -1, parent.launchedFromUid, 0, null, true, null);
12195 foundParentInTask = res == ActivityManager.START_SUCCESS;
12196 } catch (RemoteException e) {
12197 foundParentInTask = false;
12198 }
12199 mMainStack.requestFinishActivityLocked(parent.appToken, resultCode,
12200 resultData, "navigate-up");
12201 }
12202 }
12203 Binder.restoreCallingIdentity(origId);
12204 return foundParentInTask;
12205 }
12206 }
12207
Dianne Hackborn5320eb82012-05-18 12:05:04 -070012208 public int getLaunchedFromUid(IBinder activityToken) {
12209 ActivityRecord srec = ActivityRecord.forToken(activityToken);
12210 if (srec == null) {
12211 return -1;
12212 }
12213 return srec.launchedFromUid;
12214 }
12215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012216 // =========================================================
12217 // LIFETIME MANAGEMENT
12218 // =========================================================
12219
Christopher Tatef46723b2012-01-26 14:19:24 -080012220 // Returns which broadcast queue the app is the current [or imminent] receiver
12221 // on, or 'null' if the app is not an active broadcast recipient.
12222 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) {
12223 BroadcastRecord r = app.curReceiver;
12224 if (r != null) {
12225 return r.queue;
12226 }
12227
12228 // It's not the current receiver, but it might be starting up to become one
12229 synchronized (this) {
12230 for (BroadcastQueue queue : mBroadcastQueues) {
12231 r = queue.mPendingBroadcast;
12232 if (r != null && r.curApp == app) {
12233 // found it; report which queue it's in
12234 return queue;
12235 }
12236 }
12237 }
12238
12239 return null;
12240 }
12241
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012242 private final int computeOomAdjLocked(ProcessRecord app, int hiddenAdj,
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012243 int emptyAdj, ProcessRecord TOP_APP, boolean recursed, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012244 if (mAdjSeq == app.adjSeq) {
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012245 // This adjustment has already been computed. If we are calling
12246 // from the top, we may have already computed our adjustment with
12247 // an earlier hidden adjustment that isn't really for us... if
12248 // so, use the new hidden adjustment.
12249 if (!recursed && app.hidden) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012250 app.curAdj = app.curRawAdj = app.nonStoppingAdj =
12251 app.hasActivities ? hiddenAdj : emptyAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012252 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012253 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012254 }
12255
12256 if (app.thread == null) {
12257 app.adjSeq = mAdjSeq;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012258 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012259 return (app.curAdj=app.curRawAdj=ProcessList.HIDDEN_APP_MAX_ADJ);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012260 }
12261
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012262 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN;
12263 app.adjSource = null;
12264 app.adjTarget = null;
12265 app.empty = false;
12266 app.hidden = false;
12267
12268 final int activitiesSize = app.activities.size();
12269
Dianne Hackborn7d608422011-08-07 16:24:18 -070012270 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012271 // The max adjustment doesn't allow this app to be anything
12272 // below foreground, so it is not worth doing work for it.
12273 app.adjType = "fixed";
12274 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012275 app.curRawAdj = app.nonStoppingAdj = app.maxAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012276 app.hasActivities = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012277 app.foregroundActivities = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012278 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012279 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012280 // System process can do UI, and when they do we want to have
12281 // them trim their memory after the user leaves the UI. To
12282 // facilitate this, here we need to determine whether or not it
12283 // is currently showing UI.
12284 app.systemNoUi = true;
12285 if (app == TOP_APP) {
12286 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012287 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012288 } else if (activitiesSize > 0) {
12289 for (int j = 0; j < activitiesSize; j++) {
12290 final ActivityRecord r = app.activities.get(j);
12291 if (r.visible) {
12292 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012293 }
12294 if (r.app == app) {
12295 app.hasActivities = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012296 }
12297 }
12298 }
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012299 return (app.curAdj=app.maxAdj);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012300 }
12301
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012302 app.keeping = false;
12303 app.systemNoUi = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012304 app.hasActivities = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012305
The Android Open Source Project4df24232009-03-05 14:34:35 -080012306 // Determine the importance of the process, starting with most
12307 // important to least, and assign an appropriate OOM adjustment.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012308 int adj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012309 int schedGroup;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012310 boolean foregroundActivities = false;
12311 boolean interesting = false;
Christopher Tatef46723b2012-01-26 14:19:24 -080012312 BroadcastQueue queue;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012313 if (app == TOP_APP) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012314 // The last app on the list is the foreground app.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012315 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012316 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012317 app.adjType = "top-activity";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012318 foregroundActivities = true;
12319 interesting = true;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012320 app.hasActivities = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012321 } else if (app.instrumentationClass != null) {
12322 // Don't want to kill running instrumentation.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012323 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012324 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012325 app.adjType = "instrumentation";
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012326 interesting = true;
Christopher Tatef46723b2012-01-26 14:19:24 -080012327 } else if ((queue = isReceivingBroadcast(app)) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012328 // An app that is currently receiving a broadcast also
Christopher Tatef46723b2012-01-26 14:19:24 -080012329 // counts as being in the foreground for OOM killer purposes.
12330 // It's placed in a sched group based on the nature of the
12331 // broadcast as reflected by which queue it's active in.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012332 adj = ProcessList.FOREGROUND_APP_ADJ;
Christopher Tatef46723b2012-01-26 14:19:24 -080012333 schedGroup = (queue == mFgBroadcastQueue)
12334 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012335 app.adjType = "broadcast";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012336 } else if (app.executingServices.size() > 0) {
12337 // An app that is currently executing a service callback also
12338 // counts as being in the foreground.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012339 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012340 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012341 app.adjType = "exec-service";
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012342 } else {
12343 // Assume process is hidden (has activities); we will correct
12344 // later if this is not the case.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012345 adj = hiddenAdj;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012346 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012347 app.hidden = true;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012348 app.adjType = "bg-activities";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012349 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012350
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012351 boolean hasStoppingActivities = false;
12352
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012353 // Examine all activities if not already foreground.
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012354 if (!foregroundActivities && activitiesSize > 0) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012355 for (int j = 0; j < activitiesSize; j++) {
12356 final ActivityRecord r = app.activities.get(j);
12357 if (r.visible) {
12358 // App has a visible activity; only upgrade adjustment.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012359 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12360 adj = ProcessList.VISIBLE_APP_ADJ;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012361 app.adjType = "visible";
12362 }
12363 schedGroup = Process.THREAD_GROUP_DEFAULT;
12364 app.hidden = false;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012365 app.hasActivities = true;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012366 foregroundActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012367 break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012368 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012369 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12370 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012371 app.adjType = "pausing";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012372 }
Dianne Hackborn8bf0aa92011-11-29 13:54:43 -080012373 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012374 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012375 } else if (r.state == ActivityState.STOPPING) {
12376 // We will apply the actual adjustment later, because
12377 // we want to allow this process to immediately go through
12378 // any memory trimming that is in effect.
12379 app.hidden = false;
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012380 foregroundActivities = true;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012381 hasStoppingActivities = true;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012382 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012383 if (r.app == app) {
12384 app.hasActivities = true;
12385 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012386 }
12387 }
12388
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012389 if (adj == hiddenAdj && !app.hasActivities) {
12390 // Whoops, this process is completely empty as far as we know
12391 // at this point.
12392 adj = emptyAdj;
12393 app.empty = true;
12394 app.adjType = "bg-empty";
12395 }
12396
Dianne Hackborn7d608422011-08-07 16:24:18 -070012397 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012398 if (app.foregroundServices) {
12399 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012400 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012401 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012402 app.adjType = "foreground-service";
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012403 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012404 } else if (app.forcingToForeground != null) {
12405 // The user is aware of this app, so make it visible.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012406 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012407 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012408 app.adjType = "force-foreground";
12409 app.adjSource = app.forcingToForeground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012410 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012411 }
12412 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012413
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012414 if (app.foregroundServices) {
12415 interesting = true;
12416 }
12417
Dianne Hackborn7d608422011-08-07 16:24:18 -070012418 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ && app == mHeavyWeightProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012419 // We don't want to kill the current heavy-weight process.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012420 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012421 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012422 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012423 app.adjType = "heavy";
12424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012425
Dianne Hackborn7d608422011-08-07 16:24:18 -070012426 if (adj > ProcessList.HOME_APP_ADJ && app == mHomeProcess) {
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012427 // This process is hosting what we currently consider to be the
12428 // home app, so we don't want to let it go into the background.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012429 adj = ProcessList.HOME_APP_ADJ;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012430 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012431 app.hidden = false;
Dianne Hackborn83a6f452011-01-27 17:17:19 -080012432 app.adjType = "home";
12433 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012434
Dianne Hackbornf35fe232011-11-01 19:25:20 -070012435 if (adj > ProcessList.PREVIOUS_APP_ADJ && app == mPreviousProcess
12436 && app.activities.size() > 0) {
12437 // This was the previous process that showed UI to the user.
12438 // We want to try to keep it around more aggressively, to give
12439 // a good experience around switching between two apps.
12440 adj = ProcessList.PREVIOUS_APP_ADJ;
12441 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE;
12442 app.hidden = false;
12443 app.adjType = "previous";
12444 }
12445
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012446 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj
12447 + " reason=" + app.adjType);
12448
The Android Open Source Project4df24232009-03-05 14:34:35 -080012449 // By default, we use the computed adjustment. It may be changed if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012450 // there are applications dependent on our services or providers, but
12451 // this gives us a baseline and makes sure we don't get into an
12452 // infinite recursion.
12453 app.adjSeq = mAdjSeq;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012454 app.curRawAdj = app.nonStoppingAdj = adj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012455
Christopher Tate6fa95972009-06-05 18:43:55 -070012456 if (mBackupTarget != null && app == mBackupTarget.app) {
12457 // If possible we want to avoid killing apps while they're being backed up
Dianne Hackborn7d608422011-08-07 16:24:18 -070012458 if (adj > ProcessList.BACKUP_APP_ADJ) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080012459 if (DEBUG_BACKUP) Slog.v(TAG, "oom BACKUP_APP_ADJ for " + app);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012460 adj = ProcessList.BACKUP_APP_ADJ;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012461 app.adjType = "backup";
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012462 app.hidden = false;
Christopher Tate6fa95972009-06-05 18:43:55 -070012463 }
12464 }
12465
Dianne Hackborn7d608422011-08-07 16:24:18 -070012466 if (app.services.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012467 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012468 final long now = SystemClock.uptimeMillis();
12469 // This process is more important if the top activity is
12470 // bound to the service.
Dianne Hackborn860755f2010-06-03 18:47:52 -070012471 Iterator<ServiceRecord> jt = app.services.iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012472 while (jt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012473 ServiceRecord s = jt.next();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012474 if (s.startRequested) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012475 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012476 // If this process has shown some UI, let it immediately
12477 // go to the LRU list because it may be pretty heavy with
12478 // UI stuff. We'll tag it with a label just to help
12479 // debug and understand what is going on.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012480 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012481 app.adjType = "started-bg-ui-services";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012482 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012483 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012484 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012485 // This service has seen some activity within
12486 // recent memory, so we will keep its process ahead
12487 // of the background processes.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012488 if (adj > ProcessList.SERVICE_ADJ) {
12489 adj = ProcessList.SERVICE_ADJ;
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012490 app.adjType = "started-services";
12491 app.hidden = false;
12492 }
12493 }
12494 // If we have let the service slide into the background
12495 // state, still have some text describing what it is doing
12496 // even though the service no longer has an impact.
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012497 if (adj > ProcessList.SERVICE_ADJ) {
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -070012498 app.adjType = "started-bg-services";
12499 }
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080012500 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070012501 // Don't kill this process because it is doing work; it
12502 // has said it is doing work.
12503 app.keeping = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012504 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012505 if (s.connections.size() > 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012506 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012507 Iterator<ArrayList<ConnectionRecord>> kt
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012508 = s.connections.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012509 while (kt.hasNext() && adj > ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012510 ArrayList<ConnectionRecord> clist = kt.next();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012511 for (int i=0; i<clist.size() && adj > ProcessList.FOREGROUND_APP_ADJ; i++) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012512 // XXX should compute this based on the max of
12513 // all connected clients.
12514 ConnectionRecord cr = clist.get(i);
12515 if (cr.binding.client == app) {
12516 // Binding to ourself is not interesting.
12517 continue;
12518 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012519 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012520 ProcessRecord client = cr.binding.client;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012521 int clientAdj = adj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012522 int myHiddenAdj = hiddenAdj;
12523 if (myHiddenAdj > client.hiddenAdj) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012524 if (client.hiddenAdj >= ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012525 myHiddenAdj = client.hiddenAdj;
12526 } else {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012527 myHiddenAdj = ProcessList.VISIBLE_APP_ADJ;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012528 }
12529 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012530 int myEmptyAdj = emptyAdj;
12531 if (myEmptyAdj > client.emptyAdj) {
12532 if (client.emptyAdj >= ProcessList.VISIBLE_APP_ADJ) {
12533 myEmptyAdj = client.emptyAdj;
12534 } else {
12535 myEmptyAdj = ProcessList.VISIBLE_APP_ADJ;
12536 }
12537 }
12538 clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12539 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012540 String adjType = null;
12541 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) {
12542 // Not doing bind OOM management, so treat
12543 // this guy more like a started service.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012544 if (app.hasShownUi && app != mHomeProcess) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012545 // If this process has shown some UI, let it immediately
12546 // go to the LRU list because it may be pretty heavy with
12547 // UI stuff. We'll tag it with a label just to help
12548 // debug and understand what is going on.
12549 if (adj > clientAdj) {
12550 adjType = "bound-bg-ui-services";
12551 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012552 app.hidden = false;
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012553 clientAdj = adj;
12554 } else {
Dianne Hackborn599db5c2012-08-03 19:28:48 -070012555 if (now >= (s.lastActivity
12556 + ActiveServices.MAX_SERVICE_INACTIVITY)) {
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012557 // This service has not seen activity within
12558 // recent memory, so allow it to drop to the
12559 // LRU list if there is no other reason to keep
12560 // it around. We'll also tag it with a label just
12561 // to help debug and undertand what is going on.
12562 if (adj > clientAdj) {
12563 adjType = "bound-bg-services";
12564 }
12565 clientAdj = adj;
12566 }
12567 }
12568 }
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012569 if (adj > clientAdj) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012570 // If this process has recently shown UI, and
12571 // the process that is binding to it is less
12572 // important than being visible, then we don't
12573 // care about the binding as much as we care
12574 // about letting this process get into the LRU
12575 // list to be killed and restarted if needed for
12576 // memory.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070012577 if (app.hasShownUi && app != mHomeProcess
12578 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012579 adjType = "bound-bg-ui-services";
12580 } else {
12581 if ((cr.flags&(Context.BIND_ABOVE_CLIENT
12582 |Context.BIND_IMPORTANT)) != 0) {
12583 adj = clientAdj;
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012584 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0
12585 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ
12586 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12587 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12588 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012589 adj = clientAdj;
12590 } else {
Dianne Hackborn2c84cfc2011-10-31 15:39:59 -070012591 app.pendingUiClean = true;
12592 if (adj > ProcessList.VISIBLE_APP_ADJ) {
12593 adj = ProcessList.VISIBLE_APP_ADJ;
12594 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012595 }
12596 if (!client.hidden) {
12597 app.hidden = false;
12598 }
12599 if (client.keeping) {
12600 app.keeping = true;
12601 }
12602 adjType = "service";
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012603 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070012604 }
12605 if (adjType != null) {
12606 app.adjType = adjType;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012607 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12608 .REASON_SERVICE_IN_USE;
12609 app.adjSource = cr.binding.client;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012610 app.adjSourceOom = clientAdj;
Dianne Hackborn43d9ac82010-08-25 15:06:25 -070012611 app.adjTarget = s.name;
12612 }
12613 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12614 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12615 schedGroup = Process.THREAD_GROUP_DEFAULT;
12616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012617 }
12618 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012619 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) {
12620 ActivityRecord a = cr.activity;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012621 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ &&
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012622 (a.visible || a.state == ActivityState.RESUMED
12623 || a.state == ActivityState.PAUSING)) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012624 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012625 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) {
12626 schedGroup = Process.THREAD_GROUP_DEFAULT;
12627 }
12628 app.hidden = false;
12629 app.adjType = "service";
12630 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12631 .REASON_SERVICE_IN_USE;
12632 app.adjSource = a;
Dianne Hackborn905577f2011-09-07 18:31:28 -070012633 app.adjSourceOom = adj;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012634 app.adjTarget = s.name;
12635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012637 }
12638 }
12639 }
12640 }
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012641
Dianne Hackborn287952c2010-09-22 22:34:31 -070012642 // Finally, if this process has active services running in it, we
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012643 // would like to avoid killing it unless it would prevent the current
12644 // application from running. By default we put the process in
12645 // with the rest of the background processes; as we scan through
12646 // its services we may bump it up from there.
12647 if (adj > hiddenAdj) {
12648 adj = hiddenAdj;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012649 app.hidden = false;
Dianne Hackbornbcbcaa72009-09-10 10:54:46 -070012650 app.adjType = "bg-services";
12651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012652 }
12653
Dianne Hackborn7d608422011-08-07 16:24:18 -070012654 if (app.pubProviders.size() != 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012655 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012656 Iterator<ContentProviderRecord> jt = app.pubProviders.values().iterator();
Dianne Hackborn7d608422011-08-07 16:24:18 -070012657 while (jt.hasNext() && (adj > ProcessList.FOREGROUND_APP_ADJ
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012658 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE)) {
Dianne Hackborn860755f2010-06-03 18:47:52 -070012659 ContentProviderRecord cpr = jt.next();
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012660 for (int i = cpr.connections.size()-1;
12661 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ
12662 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE);
12663 i--) {
12664 ContentProviderConnection conn = cpr.connections.get(i);
12665 ProcessRecord client = conn.client;
12666 if (client == app) {
12667 // Being our own client is not interesting.
12668 continue;
12669 }
12670 int myHiddenAdj = hiddenAdj;
12671 if (myHiddenAdj > client.hiddenAdj) {
12672 if (client.hiddenAdj > ProcessList.FOREGROUND_APP_ADJ) {
12673 myHiddenAdj = client.hiddenAdj;
12674 } else {
12675 myHiddenAdj = ProcessList.FOREGROUND_APP_ADJ;
The Android Open Source Project10592532009-03-18 17:39:46 -070012676 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012677 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070012678 int myEmptyAdj = emptyAdj;
12679 if (myEmptyAdj > client.emptyAdj) {
12680 if (client.emptyAdj > ProcessList.FOREGROUND_APP_ADJ) {
12681 myEmptyAdj = client.emptyAdj;
12682 } else {
12683 myEmptyAdj = ProcessList.FOREGROUND_APP_ADJ;
12684 }
12685 }
12686 int clientAdj = computeOomAdjLocked(client, myHiddenAdj,
12687 myEmptyAdj, TOP_APP, true, doingAll);
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012688 if (adj > clientAdj) {
12689 if (app.hasShownUi && app != mHomeProcess
12690 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12691 app.adjType = "bg-ui-provider";
12692 } else {
12693 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ
12694 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ;
12695 app.adjType = "provider";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012696 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012697 if (!client.hidden) {
12698 app.hidden = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012699 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012700 if (client.keeping) {
12701 app.keeping = true;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012702 }
Dianne Hackborn6ae8d182012-05-23 13:12:42 -070012703 app.adjTypeCode = ActivityManager.RunningAppProcessInfo
12704 .REASON_PROVIDER_IN_USE;
12705 app.adjSource = client;
12706 app.adjSourceOom = clientAdj;
12707 app.adjTarget = cpr.name;
12708 }
12709 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) {
12710 schedGroup = Process.THREAD_GROUP_DEFAULT;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012711 }
12712 }
12713 // If the provider has external (non-framework) process
12714 // dependencies, ensure that its adjustment is at least
12715 // FOREGROUND_APP_ADJ.
Svetoslav Ganov25872aa2012-02-03 19:19:09 -080012716 if (cpr.hasExternalProcessHandles()) {
Dianne Hackborn7d608422011-08-07 16:24:18 -070012717 if (adj > ProcessList.FOREGROUND_APP_ADJ) {
12718 adj = ProcessList.FOREGROUND_APP_ADJ;
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012719 schedGroup = Process.THREAD_GROUP_DEFAULT;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080012720 app.hidden = false;
Dianne Hackborn287952c2010-09-22 22:34:31 -070012721 app.keeping = true;
Dianne Hackbornde42bb62009-08-05 12:26:15 -070012722 app.adjType = "provider";
Dianne Hackbornb7bb3b32010-06-06 22:47:50 -070012723 app.adjTarget = cpr.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012724 }
12725 }
12726 }
12727 }
12728
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070012729 if (adj == ProcessList.SERVICE_ADJ) {
12730 if (doingAll) {
12731 app.serviceb = mNewNumServiceProcs > (mNumServiceProcs/3);
12732 mNewNumServiceProcs++;
12733 }
12734 if (app.serviceb) {
12735 adj = ProcessList.SERVICE_B_ADJ;
12736 }
12737 } else {
12738 app.serviceb = false;
12739 }
12740
12741 app.nonStoppingAdj = adj;
12742
12743 if (hasStoppingActivities) {
12744 // Only upgrade adjustment.
12745 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) {
12746 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12747 app.adjType = "stopping";
12748 }
12749 }
12750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012751 app.curRawAdj = adj;
12752
Joe Onorato8a9b2202010-02-26 18:56:32 -080012753 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012754 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj);
12755 if (adj > app.maxAdj) {
12756 adj = app.maxAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070012757 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) {
Dianne Hackborn09c916b2009-12-08 14:50:51 -080012758 schedGroup = Process.THREAD_GROUP_DEFAULT;
12759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012760 }
Dianne Hackborn7d608422011-08-07 16:24:18 -070012761 if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070012762 app.keeping = true;
12763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012764
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012765 if (app.hasAboveClient) {
12766 // If this process has bound to any services with BIND_ABOVE_CLIENT,
12767 // then we need to drop its adjustment to be lower than the service's
12768 // in order to honor the request. We want to drop it by one adjustment
12769 // level... but there is special meaning applied to various levels so
12770 // we will skip some of them.
Dianne Hackborn7d608422011-08-07 16:24:18 -070012771 if (adj < ProcessList.FOREGROUND_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012772 // System process will not get dropped, ever
Dianne Hackborn7d608422011-08-07 16:24:18 -070012773 } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
12774 adj = ProcessList.VISIBLE_APP_ADJ;
12775 } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
12776 adj = ProcessList.PERCEPTIBLE_APP_ADJ;
12777 } else if (adj < ProcessList.HIDDEN_APP_MIN_ADJ) {
12778 adj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070012779 } else if (adj < ProcessList.HIDDEN_APP_MAX_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012780 adj++;
12781 }
12782 }
12783
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012784 int importance = app.memImportance;
12785 if (importance == 0 || adj != app.curAdj || schedGroup != app.curSchedGroup) {
12786 app.curAdj = adj;
12787 app.curSchedGroup = schedGroup;
12788 if (!interesting) {
12789 // For this reporting, if there is not something explicitly
12790 // interesting in this process then we will push it to the
12791 // background importance.
12792 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12793 } else if (adj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
12794 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12795 } else if (adj >= ProcessList.SERVICE_B_ADJ) {
12796 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12797 } else if (adj >= ProcessList.HOME_APP_ADJ) {
12798 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND;
12799 } else if (adj >= ProcessList.SERVICE_ADJ) {
12800 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE;
12801 } else if (adj >= ProcessList.HEAVY_WEIGHT_APP_ADJ) {
12802 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_CANT_SAVE_STATE;
12803 } else if (adj >= ProcessList.PERCEPTIBLE_APP_ADJ) {
12804 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE;
12805 } else if (adj >= ProcessList.VISIBLE_APP_ADJ) {
12806 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
12807 } else if (adj >= ProcessList.FOREGROUND_APP_ADJ) {
12808 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
12809 } else {
12810 importance = ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERSISTENT;
12811 }
12812 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012813
Dianne Hackborna93c2c12012-05-31 15:29:36 -070012814 int changes = importance != app.memImportance ? ProcessChangeItem.CHANGE_IMPORTANCE : 0;
12815 if (foregroundActivities != app.foregroundActivities) {
12816 changes |= ProcessChangeItem.CHANGE_ACTIVITIES;
12817 }
12818 if (changes != 0) {
12819 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Changes in " + app + ": " + changes);
12820 app.memImportance = importance;
12821 app.foregroundActivities = foregroundActivities;
12822 int i = mPendingProcessChanges.size()-1;
12823 ProcessChangeItem item = null;
12824 while (i >= 0) {
12825 item = mPendingProcessChanges.get(i);
12826 if (item.pid == app.pid) {
12827 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Re-using existing item: " + item);
12828 break;
12829 }
12830 i--;
12831 }
12832 if (i < 0) {
12833 // No existing item in pending changes; need a new one.
12834 final int NA = mAvailProcessChanges.size();
12835 if (NA > 0) {
12836 item = mAvailProcessChanges.remove(NA-1);
12837 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Retreiving available item: " + item);
12838 } else {
12839 item = new ProcessChangeItem();
12840 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Allocating new item: " + item);
12841 }
12842 item.changes = 0;
12843 item.pid = app.pid;
12844 item.uid = app.info.uid;
12845 if (mPendingProcessChanges.size() == 0) {
12846 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG,
12847 "*** Enqueueing dispatch processes changed!");
12848 mHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget();
12849 }
12850 mPendingProcessChanges.add(item);
12851 }
12852 item.changes |= changes;
12853 item.importance = importance;
12854 item.foregroundActivities = foregroundActivities;
12855 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "Item "
12856 + Integer.toHexString(System.identityHashCode(item))
12857 + " " + app.toShortString() + ": changes=" + item.changes
12858 + " importance=" + item.importance
12859 + " foreground=" + item.foregroundActivities
12860 + " type=" + app.adjType + " source=" + app.adjSource
12861 + " target=" + app.adjTarget);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070012862 }
12863
Dianne Hackbornc68c9132011-07-29 01:25:18 -070012864 return app.curRawAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012865 }
12866
12867 /**
12868 * Ask a given process to GC right now.
12869 */
12870 final void performAppGcLocked(ProcessRecord app) {
12871 try {
12872 app.lastRequestedGc = SystemClock.uptimeMillis();
12873 if (app.thread != null) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012874 if (app.reportLowMemory) {
12875 app.reportLowMemory = false;
12876 app.thread.scheduleLowMemory();
12877 } else {
12878 app.thread.processInBackground();
12879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012880 }
12881 } catch (Exception e) {
12882 // whatever.
12883 }
12884 }
12885
12886 /**
12887 * Returns true if things are idle enough to perform GCs.
12888 */
Josh Bartel7f208742010-02-25 11:01:44 -060012889 private final boolean canGcNowLocked() {
Christopher Tatef46723b2012-01-26 14:19:24 -080012890 boolean processingBroadcasts = false;
12891 for (BroadcastQueue q : mBroadcastQueues) {
12892 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) {
12893 processingBroadcasts = true;
12894 }
12895 }
12896 return !processingBroadcasts
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070012897 && (mSleeping || (mMainStack.mResumedActivity != null &&
12898 mMainStack.mResumedActivity.idle));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012899 }
12900
12901 /**
12902 * Perform GCs on all processes that are waiting for it, but only
12903 * if things are idle.
12904 */
12905 final void performAppGcsLocked() {
12906 final int N = mProcessesToGc.size();
12907 if (N <= 0) {
12908 return;
12909 }
Josh Bartel7f208742010-02-25 11:01:44 -060012910 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012911 while (mProcessesToGc.size() > 0) {
12912 ProcessRecord proc = mProcessesToGc.remove(0);
Dianne Hackborn7d608422011-08-07 16:24:18 -070012913 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012914 if ((proc.lastRequestedGc+GC_MIN_INTERVAL)
12915 <= SystemClock.uptimeMillis()) {
12916 // To avoid spamming the system, we will GC processes one
12917 // at a time, waiting a few seconds between each.
12918 performAppGcLocked(proc);
12919 scheduleAppGcsLocked();
12920 return;
12921 } else {
12922 // It hasn't been long enough since we last GCed this
12923 // process... put it in the list to wait for its time.
12924 addProcessToGcListLocked(proc);
12925 break;
12926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012927 }
12928 }
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012929
12930 scheduleAppGcsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012931 }
12932 }
12933
12934 /**
12935 * If all looks good, perform GCs on all processes waiting for them.
12936 */
12937 final void performAppGcsIfAppropriateLocked() {
Josh Bartel7f208742010-02-25 11:01:44 -060012938 if (canGcNowLocked()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012939 performAppGcsLocked();
12940 return;
12941 }
12942 // Still not idle, wait some more.
12943 scheduleAppGcsLocked();
12944 }
12945
12946 /**
12947 * Schedule the execution of all pending app GCs.
12948 */
12949 final void scheduleAppGcsLocked() {
12950 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG);
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012951
12952 if (mProcessesToGc.size() > 0) {
12953 // Schedule a GC for the time to the next process.
12954 ProcessRecord proc = mProcessesToGc.get(0);
12955 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG);
12956
Dianne Hackbornce86ba82011-07-13 19:33:41 -070012957 long when = proc.lastRequestedGc + GC_MIN_INTERVAL;
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012958 long now = SystemClock.uptimeMillis();
12959 if (when < (now+GC_TIMEOUT)) {
12960 when = now + GC_TIMEOUT;
12961 }
12962 mHandler.sendMessageAtTime(msg, when);
12963 }
12964 }
12965
12966 /**
12967 * Add a process to the array of processes waiting to be GCed. Keeps the
12968 * list in sorted order by the last GC time. The process can't already be
12969 * on the list.
12970 */
12971 final void addProcessToGcListLocked(ProcessRecord proc) {
12972 boolean added = false;
12973 for (int i=mProcessesToGc.size()-1; i>=0; i--) {
12974 if (mProcessesToGc.get(i).lastRequestedGc <
12975 proc.lastRequestedGc) {
12976 added = true;
12977 mProcessesToGc.add(i+1, proc);
12978 break;
12979 }
12980 }
12981 if (!added) {
12982 mProcessesToGc.add(0, proc);
12983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012984 }
12985
12986 /**
12987 * Set up to ask a process to GC itself. This will either do it
12988 * immediately, or put it on the list of processes to gc the next
12989 * time things are idle.
12990 */
12991 final void scheduleAppGcLocked(ProcessRecord app) {
12992 long now = SystemClock.uptimeMillis();
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012993 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012994 return;
12995 }
12996 if (!mProcessesToGc.contains(app)) {
Dianne Hackbornfd12af42009-08-27 00:44:33 -070012997 addProcessToGcListLocked(app);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012998 scheduleAppGcsLocked();
12999 }
13000 }
13001
Dianne Hackborn287952c2010-09-22 22:34:31 -070013002 final void checkExcessivePowerUsageLocked(boolean doKills) {
13003 updateCpuStatsNow();
13004
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013005 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013006 boolean doWakeKills = doKills;
13007 boolean doCpuKills = doKills;
13008 if (mLastPowerCheckRealtime == 0) {
13009 doWakeKills = false;
13010 }
13011 if (mLastPowerCheckUptime == 0) {
13012 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013013 }
13014 if (stats.isScreenOn()) {
Dianne Hackborn287952c2010-09-22 22:34:31 -070013015 doWakeKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013016 }
13017 final long curRealtime = SystemClock.elapsedRealtime();
Dianne Hackborn287952c2010-09-22 22:34:31 -070013018 final long realtimeSince = curRealtime - mLastPowerCheckRealtime;
13019 final long curUptime = SystemClock.uptimeMillis();
13020 final long uptimeSince = curUptime - mLastPowerCheckUptime;
13021 mLastPowerCheckRealtime = curRealtime;
13022 mLastPowerCheckUptime = curUptime;
13023 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) {
13024 doWakeKills = false;
13025 }
13026 if (uptimeSince < CPU_MIN_CHECK_DURATION) {
13027 doCpuKills = false;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013028 }
13029 int i = mLruProcesses.size();
13030 while (i > 0) {
13031 i--;
13032 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013033 if (!app.keeping) {
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013034 long wtime;
13035 synchronized (stats) {
13036 wtime = stats.getProcessWakeTime(app.info.uid,
13037 app.pid, curRealtime);
13038 }
Dianne Hackborn287952c2010-09-22 22:34:31 -070013039 long wtimeUsed = wtime - app.lastWakeTime;
13040 long cputimeUsed = app.curCpuTime - app.lastCpuTime;
13041 if (DEBUG_POWER) {
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013042 StringBuilder sb = new StringBuilder(128);
13043 sb.append("Wake for ");
13044 app.toShortString(sb);
13045 sb.append(": over ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013046 TimeUtils.formatDuration(realtimeSince, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013047 sb.append(" used ");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013048 TimeUtils.formatDuration(wtimeUsed, sb);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013049 sb.append(" (");
Dianne Hackborn287952c2010-09-22 22:34:31 -070013050 sb.append((wtimeUsed*100)/realtimeSince);
13051 sb.append("%)");
13052 Slog.i(TAG, sb.toString());
13053 sb.setLength(0);
13054 sb.append("CPU for ");
13055 app.toShortString(sb);
13056 sb.append(": over ");
13057 TimeUtils.formatDuration(uptimeSince, sb);
13058 sb.append(" used ");
13059 TimeUtils.formatDuration(cputimeUsed, sb);
13060 sb.append(" (");
13061 sb.append((cputimeUsed*100)/uptimeSince);
Dianne Hackborn1ebccf52010-08-15 13:04:34 -070013062 sb.append("%)");
13063 Slog.i(TAG, sb.toString());
13064 }
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013065 // If a process has held a wake lock for more
13066 // than 50% of the time during this period,
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013067 // that sounds bad. Kill!
Dianne Hackborn287952c2010-09-22 22:34:31 -070013068 if (doWakeKills && realtimeSince > 0
13069 && ((wtimeUsed*100)/realtimeSince) >= 50) {
13070 synchronized (stats) {
13071 stats.reportExcessiveWakeLocked(app.info.uid, app.processName,
13072 realtimeSince, wtimeUsed);
13073 }
13074 Slog.w(TAG, "Excessive wake lock in " + app.processName
13075 + " (pid " + app.pid + "): held " + wtimeUsed
13076 + " during " + realtimeSince);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013077 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13078 app.processName, app.setAdj, "excessive wake lock");
13079 Process.killProcessQuiet(app.pid);
Dianne Hackborn287952c2010-09-22 22:34:31 -070013080 } else if (doCpuKills && uptimeSince > 0
13081 && ((cputimeUsed*100)/uptimeSince) >= 50) {
13082 synchronized (stats) {
13083 stats.reportExcessiveCpuLocked(app.info.uid, app.processName,
13084 uptimeSince, cputimeUsed);
13085 }
13086 Slog.w(TAG, "Excessive CPU in " + app.processName
13087 + " (pid " + app.pid + "): used " + cputimeUsed
13088 + " during " + uptimeSince);
13089 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13090 app.processName, app.setAdj, "excessive cpu");
13091 Process.killProcessQuiet(app.pid);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013092 } else {
13093 app.lastWakeTime = wtime;
Dianne Hackborn287952c2010-09-22 22:34:31 -070013094 app.lastCpuTime = app.curCpuTime;
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013095 }
13096 }
13097 }
13098 }
13099
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013100 private final boolean updateOomAdjLocked(ProcessRecord app, int hiddenAdj,
13101 int emptyAdj, ProcessRecord TOP_APP, boolean doingAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013102 app.hiddenAdj = hiddenAdj;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013103 app.emptyAdj = emptyAdj;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013104
13105 if (app.thread == null) {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013106 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013107 }
13108
Dianne Hackborn287952c2010-09-22 22:34:31 -070013109 final boolean wasKeeping = app.keeping;
13110
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013111 boolean success = true;
13112
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013113 computeOomAdjLocked(app, hiddenAdj, emptyAdj, TOP_APP, false, doingAll);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013114
Jeff Brown10e89712011-07-08 18:52:57 -070013115 if (app.curRawAdj != app.setRawAdj) {
Jeff Brown10e89712011-07-08 18:52:57 -070013116 if (wasKeeping && !app.keeping) {
13117 // This app is no longer something we want to keep. Note
13118 // its current wake lock time to later know to kill it if
13119 // it is not behaving well.
13120 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics();
13121 synchronized (stats) {
13122 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid,
13123 app.pid, SystemClock.elapsedRealtime());
13124 }
13125 app.lastCpuTime = app.curCpuTime;
13126 }
13127
13128 app.setRawAdj = app.curRawAdj;
13129 }
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013130
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013131 if (app.curAdj != app.setAdj) {
13132 if (Process.setOomAdj(app.pid, app.curAdj)) {
Dianne Hackbornbbb09ac2011-11-30 11:31:29 -080013133 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013134 TAG, "Set " + app.pid + " " + app.processName +
13135 " adj " + app.curAdj + ": " + app.adjType);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013136 app.setAdj = app.curAdj;
Jeff Brown10e89712011-07-08 18:52:57 -070013137 } else {
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013138 success = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013139 Slog.w(TAG, "Failed setting oom adj of " + app + " to " + app.curAdj);
Jeff Brown10e89712011-07-08 18:52:57 -070013140 }
13141 }
13142 if (app.setSchedGroup != app.curSchedGroup) {
13143 app.setSchedGroup = app.curSchedGroup;
13144 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG,
13145 "Setting process group of " + app.processName
13146 + " to " + app.curSchedGroup);
13147 if (app.waitingToKill != null &&
13148 app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) {
13149 Slog.i(TAG, "Killing " + app.toShortString() + ": " + app.waitingToKill);
13150 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13151 app.processName, app.setAdj, app.waitingToKill);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -070013152 app.killedBackground = true;
Jeff Brown10e89712011-07-08 18:52:57 -070013153 Process.killProcessQuiet(app.pid);
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013154 success = false;
Jeff Brown10e89712011-07-08 18:52:57 -070013155 } else {
13156 if (true) {
13157 long oldId = Binder.clearCallingIdentity();
13158 try {
13159 Process.setProcessGroup(app.pid, app.curSchedGroup);
13160 } catch (Exception e) {
13161 Slog.w(TAG, "Failed setting process group of " + app.pid
13162 + " to " + app.curSchedGroup);
13163 e.printStackTrace();
13164 } finally {
13165 Binder.restoreCallingIdentity(oldId);
Dianne Hackborn9adb9c32010-08-13 14:09:56 -070013166 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013167 } else {
Jeff Brown10e89712011-07-08 18:52:57 -070013168 if (app.thread != null) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013169 try {
Jeff Brown10e89712011-07-08 18:52:57 -070013170 app.thread.setSchedulingGroup(app.curSchedGroup);
13171 } catch (RemoteException e) {
Dianne Hackborn06de2ea2009-05-21 12:56:43 -070013172 }
13173 }
13174 }
13175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013176 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013177 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013178 }
13179
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013180 private final ActivityRecord resumedAppLocked() {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013181 ActivityRecord resumedActivity = mMainStack.mResumedActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013182 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -080013183 resumedActivity = mMainStack.mPausingActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013184 if (resumedActivity == null || resumedActivity.app == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013185 resumedActivity = mMainStack.topRunningActivityLocked(null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013186 }
13187 }
13188 return resumedActivity;
13189 }
13190
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013191 final boolean updateOomAdjLocked(ProcessRecord app) {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013192 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013193 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13194 int curAdj = app.curAdj;
Dianne Hackborn7d608422011-08-07 16:24:18 -070013195 final boolean wasHidden = curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13196 && curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013197
13198 mAdjSeq++;
13199
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013200 boolean success = updateOomAdjLocked(app, app.hiddenAdj, app.emptyAdj,
13201 TOP_APP, false);
Dianne Hackborn7d608422011-08-07 16:24:18 -070013202 final boolean nowHidden = app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ
13203 && app.curAdj <= ProcessList.HIDDEN_APP_MAX_ADJ;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013204 if (nowHidden != wasHidden) {
13205 // Changed to/from hidden state, so apps after it in the LRU
13206 // list may also be changed.
13207 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013208 }
Dianne Hackborn295e3c22011-08-25 13:19:08 -070013209 return success;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013210 }
13211
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013212 final void updateOomAdjLocked() {
Dianne Hackborn01e4cfc2010-06-24 15:07:24 -070013213 final ActivityRecord TOP_ACT = resumedAppLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013214 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null;
13215
13216 if (false) {
13217 RuntimeException e = new RuntimeException();
13218 e.fillInStackTrace();
Joe Onorato8a9b2202010-02-26 18:56:32 -080013219 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013220 }
13221
13222 mAdjSeq++;
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013223 mNewNumServiceProcs = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013224
Dianne Hackborn5ce7d282010-02-12 19:30:02 -080013225 // Let's determine how many processes we have running vs.
13226 // how many slots we have for background processes; we may want
13227 // to put multiple processes in a slot of there are enough of
13228 // them.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013229 int numSlots = (ProcessList.HIDDEN_APP_MAX_ADJ
13230 - ProcessList.HIDDEN_APP_MIN_ADJ + 1) / 2;
13231 int emptyFactor = (mLruProcesses.size()-mNumNonHiddenProcs-mNumHiddenProcs)/numSlots;
13232 if (emptyFactor < 1) emptyFactor = 1;
13233 int hiddenFactor = (mNumHiddenProcs > 0 ? mNumHiddenProcs : 1)/numSlots;
13234 if (hiddenFactor < 1) hiddenFactor = 1;
13235 int stepHidden = 0;
13236 int stepEmpty = 0;
13237 final int emptyProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
13238 final int hiddenProcessLimit = mProcessLimit > 1 ? mProcessLimit / 2 : mProcessLimit;
Dianne Hackborn8633e682010-04-22 16:03:41 -070013239 int numHidden = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013240 int numEmpty = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013241 int numTrimming = 0;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013242
13243 mNumNonHiddenProcs = 0;
13244 mNumHiddenProcs = 0;
13245
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013246 // First update the OOM adjustment for each of the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013247 // application processes based on their current state.
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013248 int i = mLruProcesses.size();
Dianne Hackborn7d608422011-08-07 16:24:18 -070013249 int curHiddenAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013250 int nextHiddenAdj = curHiddenAdj+1;
13251 int curEmptyAdj = ProcessList.HIDDEN_APP_MIN_ADJ;
13252 int nextEmptyAdj = curEmptyAdj+2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013253 while (i > 0) {
13254 i--;
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013255 ProcessRecord app = mLruProcesses.get(i);
Joe Onorato8a9b2202010-02-26 18:56:32 -080013256 //Slog.i(TAG, "OOM " + app + ": cur hidden=" + curHiddenAdj);
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013257 updateOomAdjLocked(app, curHiddenAdj, curEmptyAdj, TOP_APP, true);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013258 if (!app.killedBackground) {
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013259 if (app.curRawAdj == curHiddenAdj && app.hasActivities) {
13260 // This process was assigned as a hidden process... step the
13261 // hidden level.
13262 mNumHiddenProcs++;
13263 if (curHiddenAdj != nextHiddenAdj) {
13264 stepHidden++;
13265 if (stepHidden >= hiddenFactor) {
13266 stepHidden = 0;
13267 curHiddenAdj = nextHiddenAdj;
13268 nextHiddenAdj += 2;
13269 if (nextHiddenAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13270 nextHiddenAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13271 }
13272 }
13273 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013274 numHidden++;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013275 if (numHidden > hiddenProcessLimit) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013276 Slog.i(TAG, "No longer want " + app.processName
13277 + " (pid " + app.pid + "): hidden #" + numHidden);
13278 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13279 app.processName, app.setAdj, "too many background");
13280 app.killedBackground = true;
13281 Process.killProcessQuiet(app.pid);
Dianne Hackborn8633e682010-04-22 16:03:41 -070013282 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013283 } else {
13284 if (app.curRawAdj == curEmptyAdj || app.curRawAdj == curHiddenAdj) {
13285 // This process was assigned as an empty process... step the
13286 // empty level.
13287 if (curEmptyAdj != nextEmptyAdj) {
13288 stepEmpty++;
13289 if (stepEmpty >= emptyFactor) {
13290 stepEmpty = 0;
13291 curEmptyAdj = nextEmptyAdj;
13292 nextEmptyAdj += 2;
13293 if (nextEmptyAdj > ProcessList.HIDDEN_APP_MAX_ADJ) {
13294 nextEmptyAdj = ProcessList.HIDDEN_APP_MAX_ADJ;
13295 }
13296 }
13297 }
13298 } else if (app.curRawAdj < ProcessList.HIDDEN_APP_MIN_ADJ) {
13299 mNumNonHiddenProcs++;
13300 }
13301 if (app.curAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) {
13302 numEmpty++;
13303 if (numEmpty > emptyProcessLimit) {
13304 Slog.i(TAG, "No longer want " + app.processName
13305 + " (pid " + app.pid + "): empty #" + numEmpty);
13306 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13307 app.processName, app.setAdj, "too many background");
13308 app.killedBackground = true;
13309 Process.killProcessQuiet(app.pid);
13310 }
13311 }
Dianne Hackborn8633e682010-04-22 16:03:41 -070013312 }
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013313 if (app.isolated && app.services.size() <= 0) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013314 // If this is an isolated process, and there are no
13315 // services running in it, then the process is no longer
13316 // needed. We agressively kill these because we can by
13317 // definition not re-use the same process again, and it is
13318 // good to avoid having whatever code was running in them
13319 // left sitting around after no longer needed.
13320 Slog.i(TAG, "Isolated process " + app.processName
13321 + " (pid " + app.pid + ") no longer needed");
13322 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13323 app.processName, app.setAdj, "isolated not needed");
13324 app.killedBackground = true;
13325 Process.killProcessQuiet(app.pid);
13326 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013327 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13328 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
13329 && !app.killedBackground) {
13330 numTrimming++;
13331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013332 }
13333 }
13334
Dianne Hackborne02c88a2011-10-28 13:58:15 -070013335 mNumServiceProcs = mNewNumServiceProcs;
13336
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013337 // Now determine the memory trimming level of background processes.
13338 // Unfortunately we need to start at the back of the list to do this
13339 // properly. We only do this if the number of background apps we
13340 // are managing to keep around is less than half the maximum we desire;
13341 // if we are keeping a good number around, we'll let them use whatever
13342 // memory they want.
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013343 if (numHidden <= (ProcessList.MAX_HIDDEN_APPS/4)
13344 && numEmpty <= (ProcessList.MAX_HIDDEN_APPS/4)) {
13345 final int numHiddenAndEmpty = numHidden + numEmpty;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013346 final int N = mLruProcesses.size();
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013347 int factor = numTrimming/3;
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013348 int minFactor = 2;
13349 if (mHomeProcess != null) minFactor++;
13350 if (mPreviousProcess != null) minFactor++;
13351 if (factor < minFactor) factor = minFactor;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013352 int step = 0;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013353 int fgTrimLevel;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013354 if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/5)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013355 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL;
Dianne Hackbornee7621c2012-08-13 16:42:18 -070013356 } else if (numHiddenAndEmpty <= (ProcessList.MAX_HIDDEN_APPS/3)) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013357 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW;
13358 } else {
13359 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE;
13360 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013361 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013362 for (i=0; i<N; i++) {
13363 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013364 if (app.nonStoppingAdj >= ProcessList.HOME_APP_ADJ
13365 && app.nonStoppingAdj != ProcessList.SERVICE_B_ADJ
Dianne Hackbornd8c98fe2011-11-15 11:29:38 -080013366 && !app.killedBackground) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013367 if (app.trimMemoryLevel < curLevel && app.thread != null) {
13368 try {
13369 app.thread.scheduleTrimMemory(curLevel);
13370 } catch (RemoteException e) {
13371 }
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013372 if (false) {
13373 // For now we won't do this; our memory trimming seems
13374 // to be good enough at this point that destroying
13375 // activities causes more harm than good.
13376 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE
13377 && app != mHomeProcess && app != mPreviousProcess) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013378 // Need to do this on its own message because the stack may not
13379 // be in a consistent state at this point.
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013380 // For these apps we will also finish their activities
13381 // to help them free memory.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013382 mMainStack.scheduleDestroyActivities(app, false, "trim");
Dianne Hackborn77eaaf02011-12-05 18:05:31 -080013383 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013384 }
13385 }
13386 app.trimMemoryLevel = curLevel;
13387 step++;
13388 if (step >= factor) {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013389 step = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013390 switch (curLevel) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013391 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE:
13392 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013393 break;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013394 case ComponentCallbacks2.TRIM_MEMORY_MODERATE:
13395 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013396 break;
13397 }
13398 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013399 } else if (app.nonStoppingAdj == ProcessList.HEAVY_WEIGHT_APP_ADJ) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013400 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013401 && app.thread != null) {
13402 try {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013403 app.thread.scheduleTrimMemory(
13404 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND);
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013405 } catch (RemoteException e) {
13406 }
13407 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013408 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND;
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013409 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013410 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013411 && app.pendingUiClean) {
13412 // If this application is now in the background and it
13413 // had done UI, then give it the special trim level to
13414 // have it free UI resources.
13415 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN;
13416 if (app.trimMemoryLevel < level && app.thread != null) {
13417 try {
13418 app.thread.scheduleTrimMemory(level);
13419 } catch (RemoteException e) {
13420 }
13421 }
13422 app.pendingUiClean = false;
13423 }
13424 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) {
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013425 try {
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013426 app.thread.scheduleTrimMemory(fgTrimLevel);
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013427 } catch (RemoteException e) {
13428 }
13429 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013430 app.trimMemoryLevel = fgTrimLevel;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013431 }
13432 }
13433 } else {
13434 final int N = mLruProcesses.size();
13435 for (i=0; i<N; i++) {
13436 ProcessRecord app = mLruProcesses.get(i);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -070013437 if ((app.nonStoppingAdj > ProcessList.VISIBLE_APP_ADJ || app.systemNoUi)
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013438 && app.pendingUiClean) {
13439 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN
13440 && app.thread != null) {
13441 try {
13442 app.thread.scheduleTrimMemory(
13443 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN);
13444 } catch (RemoteException e) {
13445 }
13446 }
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013447 app.pendingUiClean = false;
Dianne Hackbornc68c9132011-07-29 01:25:18 -070013448 }
Dianne Hackborn27ff9132012-03-06 14:57:58 -080013449 app.trimMemoryLevel = 0;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013450 }
13451 }
13452
13453 if (mAlwaysFinishActivities) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -070013454 // Need to do this on its own message because the stack may not
13455 // be in a consistent state at this point.
13456 mMainStack.scheduleDestroyActivities(null, false, "always-finish");
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013458 }
13459
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070013460 final void trimApplications() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013461 synchronized (this) {
13462 int i;
13463
13464 // First remove any unused application processes whose package
13465 // has been removed.
13466 for (i=mRemovedProcesses.size()-1; i>=0; i--) {
13467 final ProcessRecord app = mRemovedProcesses.get(i);
13468 if (app.activities.size() == 0
13469 && app.curReceiver == null && app.services.size() == 0) {
Joe Onorato8a9b2202010-02-26 18:56:32 -080013470 Slog.i(
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013471 TAG, "Exiting empty application process "
13472 + app.processName + " ("
13473 + (app.thread != null ? app.thread.asBinder() : null)
13474 + ")\n");
13475 if (app.pid > 0 && app.pid != MY_PID) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070013476 EventLog.writeEvent(EventLogTags.AM_KILL, app.pid,
13477 app.processName, app.setAdj, "empty");
13478 Process.killProcessQuiet(app.pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013479 } else {
13480 try {
13481 app.thread.scheduleExit();
13482 } catch (Exception e) {
13483 // Ignore exceptions.
13484 }
13485 }
Dianne Hackborn130b0d22011-07-26 22:07:48 -070013486 cleanUpApplicationRecordLocked(app, false, true, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013487 mRemovedProcesses.remove(i);
13488
13489 if (app.persistent) {
13490 if (app.persistent) {
Dianne Hackborna0c283e2012-02-09 10:47:01 -080013491 addAppLocked(app.info, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013492 }
13493 }
13494 }
13495 }
13496
Dianne Hackbornce86ba82011-07-13 19:33:41 -070013497 // Now update the oom adj for all processes.
13498 updateOomAdjLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013499 }
13500 }
13501
13502 /** This method sends the specified signal to each of the persistent apps */
13503 public void signalPersistentProcesses(int sig) throws RemoteException {
13504 if (sig != Process.SIGNAL_USR1) {
13505 throw new SecurityException("Only SIGNAL_USR1 is allowed");
13506 }
13507
13508 synchronized (this) {
13509 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES)
13510 != PackageManager.PERMISSION_GRANTED) {
13511 throw new SecurityException("Requires permission "
13512 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES);
13513 }
13514
Dianne Hackborndd71fc82009-12-16 19:24:32 -080013515 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
13516 ProcessRecord r = mLruProcesses.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013517 if (r.thread != null && r.persistent) {
13518 Process.sendSignal(r.pid, sig);
13519 }
13520 }
13521 }
13522 }
13523
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013524 private void stopProfilerLocked(ProcessRecord proc, String path, int profileType) {
13525 if (proc == null || proc == mProfileProc) {
13526 proc = mProfileProc;
13527 path = mProfileFile;
13528 profileType = mProfileType;
13529 clearProfilerLocked();
13530 }
13531 if (proc == null) {
13532 return;
13533 }
13534 try {
13535 proc.thread.profilerControl(false, path, null, profileType);
13536 } catch (RemoteException e) {
13537 throw new IllegalStateException("Process disappeared");
13538 }
13539 }
13540
13541 private void clearProfilerLocked() {
13542 if (mProfileFd != null) {
13543 try {
13544 mProfileFd.close();
13545 } catch (IOException e) {
13546 }
13547 }
13548 mProfileApp = null;
13549 mProfileProc = null;
13550 mProfileFile = null;
13551 mProfileType = 0;
13552 mAutoStopProfiler = false;
13553 }
13554
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013555 public boolean profileControl(String process, boolean start,
Romain Guy7eabe552011-07-21 14:56:34 -070013556 String path, ParcelFileDescriptor fd, int profileType) throws RemoteException {
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013557
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013558 try {
13559 synchronized (this) {
13560 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13561 // its own permission.
13562 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13563 != PackageManager.PERMISSION_GRANTED) {
13564 throw new SecurityException("Requires permission "
13565 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013566 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013567
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013568 if (start && fd == null) {
13569 throw new IllegalArgumentException("null fd");
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013570 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013571
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013572 ProcessRecord proc = null;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013573 if (process != null) {
13574 try {
13575 int pid = Integer.parseInt(process);
13576 synchronized (mPidsSelfLocked) {
13577 proc = mPidsSelfLocked.get(pid);
13578 }
13579 } catch (NumberFormatException e) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013580 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013581
13582 if (proc == null) {
13583 HashMap<String, SparseArray<ProcessRecord>> all
13584 = mProcessNames.getMap();
13585 SparseArray<ProcessRecord> procs = all.get(process);
13586 if (procs != null && procs.size() > 0) {
13587 proc = procs.valueAt(0);
13588 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013589 }
13590 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013591
13592 if (start && (proc == null || proc.thread == null)) {
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013593 throw new IllegalArgumentException("Unknown process: " + process);
13594 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013595
13596 if (start) {
13597 stopProfilerLocked(null, null, 0);
13598 setProfileApp(proc.info, proc.processName, path, fd, false);
13599 mProfileProc = proc;
13600 mProfileType = profileType;
13601 try {
13602 fd = fd.dup();
13603 } catch (IOException e) {
13604 fd = null;
13605 }
13606 proc.thread.profilerControl(start, path, fd, profileType);
13607 fd = null;
13608 mProfileFd = null;
13609 } else {
13610 stopProfilerLocked(proc, path, profileType);
13611 if (fd != null) {
13612 try {
13613 fd.close();
13614 } catch (IOException e) {
13615 }
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013616 }
13617 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070013618
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013619 return true;
Dianne Hackborn9c8dd552009-06-23 19:22:52 -070013620 }
13621 } catch (RemoteException e) {
13622 throw new IllegalStateException("Process disappeared");
13623 } finally {
13624 if (fd != null) {
13625 try {
13626 fd.close();
13627 } catch (IOException e) {
13628 }
The Android Open Source Projectf5b4b982009-03-05 20:00:43 -080013629 }
13630 }
13631 }
Andy McFadden824c5102010-07-09 16:26:57 -070013632
13633 public boolean dumpHeap(String process, boolean managed,
13634 String path, ParcelFileDescriptor fd) throws RemoteException {
13635
13636 try {
13637 synchronized (this) {
13638 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to
13639 // its own permission (same as profileControl).
13640 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER)
13641 != PackageManager.PERMISSION_GRANTED) {
13642 throw new SecurityException("Requires permission "
13643 + android.Manifest.permission.SET_ACTIVITY_WATCHER);
13644 }
13645
13646 if (fd == null) {
13647 throw new IllegalArgumentException("null fd");
13648 }
13649
13650 ProcessRecord proc = null;
13651 try {
13652 int pid = Integer.parseInt(process);
13653 synchronized (mPidsSelfLocked) {
13654 proc = mPidsSelfLocked.get(pid);
13655 }
13656 } catch (NumberFormatException e) {
13657 }
13658
13659 if (proc == null) {
13660 HashMap<String, SparseArray<ProcessRecord>> all
13661 = mProcessNames.getMap();
13662 SparseArray<ProcessRecord> procs = all.get(process);
13663 if (procs != null && procs.size() > 0) {
13664 proc = procs.valueAt(0);
13665 }
13666 }
13667
13668 if (proc == null || proc.thread == null) {
13669 throw new IllegalArgumentException("Unknown process: " + process);
13670 }
13671
Dianne Hackbornf02e57b2011-03-01 22:21:04 -080013672 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"));
13673 if (!isDebuggable) {
Andy McFadden824c5102010-07-09 16:26:57 -070013674 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
13675 throw new SecurityException("Process not debuggable: " + proc);
13676 }
13677 }
13678
13679 proc.thread.dumpHeap(managed, path, fd);
13680 fd = null;
13681 return true;
13682 }
13683 } catch (RemoteException e) {
13684 throw new IllegalStateException("Process disappeared");
13685 } finally {
13686 if (fd != null) {
13687 try {
13688 fd.close();
13689 } catch (IOException e) {
13690 }
13691 }
13692 }
13693 }
13694
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013695 /** In this method we try to acquire our lock to make sure that we have not deadlocked */
13696 public void monitor() {
13697 synchronized (this) { }
13698 }
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013699
Dianne Hackborna573f6a2012-02-09 16:12:18 -080013700 void onCoreSettingsChange(Bundle settings) {
Svetoslav Ganov54d068e2011-03-02 12:58:40 -080013701 for (int i = mLruProcesses.size() - 1; i >= 0; i--) {
13702 ProcessRecord processRecord = mLruProcesses.get(i);
13703 try {
13704 if (processRecord.thread != null) {
13705 processRecord.thread.setCoreSettings(settings);
13706 }
13707 } catch (RemoteException re) {
13708 /* ignore */
13709 }
13710 }
13711 }
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013712
13713 // Multi-user methods
13714
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013715 @Override
Amith Yamasani742a6712011-05-04 14:49:28 -070013716 public boolean switchUser(int userId) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013717 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13718 != PackageManager.PERMISSION_GRANTED) {
13719 String msg = "Permission Denial: switchUser() from pid="
13720 + Binder.getCallingPid()
13721 + ", uid=" + Binder.getCallingUid()
13722 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13723 Slog.w(TAG, msg);
13724 throw new SecurityException(msg);
Amith Yamasani742a6712011-05-04 14:49:28 -070013725 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013726 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013727 if (mCurrentUserId == userId) {
13728 return true;
13729 }
13730
13731 // If the user we are switching to is not currently started, then
13732 // we need to start it now.
13733 if (mStartedUsers.get(userId) == null) {
13734 mStartedUsers.put(userId, new UserStartedState(new UserHandle(userId), false));
Amith Yamasani742a6712011-05-04 14:49:28 -070013735 }
13736
13737 mCurrentUserId = userId;
13738 boolean haveActivities = mMainStack.switchUser(userId);
13739 if (!haveActivities) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013740 startHomeActivityLocked(userId, mStartedUsers.get(userId));
Amith Yamasani742a6712011-05-04 14:49:28 -070013741 }
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013742 }
Amith Yamasani13593602012-03-22 16:16:17 -070013743
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013744 long ident = Binder.clearCallingIdentity();
13745 try {
13746 // Inform of user switch
13747 Intent addedIntent = new Intent(Intent.ACTION_USER_SWITCHED);
13748 addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070013749 mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL,
13750 android.Manifest.permission.MANAGE_USERS);
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013751 } finally {
13752 Binder.restoreCallingIdentity(ident);
13753 }
Amith Yamasani13593602012-03-22 16:16:17 -070013754
Amith Yamasani4b2e9342011-03-31 12:38:53 -070013755 return true;
13756 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013757
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013758 void finishUserSwitch(UserStartedState uss) {
13759 synchronized (this) {
13760 if (uss.mState == UserStartedState.STATE_BOOTING
13761 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
13762 uss.mState = UserStartedState.STATE_RUNNING;
13763 broadcastIntentLocked(null, null,
13764 new Intent(Intent.ACTION_BOOT_COMPLETED, null),
13765 null, null, 0, null, null,
13766 android.Manifest.permission.RECEIVE_BOOT_COMPLETED,
13767 false, false, MY_PID, Process.SYSTEM_UID, uss.mHandle.getIdentifier());
13768 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013769 }
Amith Yamasani52f1d752012-03-28 18:19:29 -070013770 }
13771
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013772 @Override
13773 public int stopUser(final int userId, final IStopUserCallback callback) {
13774 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13775 != PackageManager.PERMISSION_GRANTED) {
13776 String msg = "Permission Denial: switchUser() from pid="
13777 + Binder.getCallingPid()
13778 + ", uid=" + Binder.getCallingUid()
13779 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13780 Slog.w(TAG, msg);
13781 throw new SecurityException(msg);
13782 }
13783 if (userId <= 0) {
13784 throw new IllegalArgumentException("Can't stop primary user " + userId);
13785 }
Amith Yamasani13593602012-03-22 16:16:17 -070013786 synchronized (this) {
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013787 if (mCurrentUserId == userId) {
13788 return ActivityManager.USER_OP_IS_CURRENT;
13789 }
13790
13791 final UserStartedState uss = mStartedUsers.get(userId);
13792 if (uss == null) {
13793 // User is not started, nothing to do... but we do need to
13794 // callback if requested.
13795 if (callback != null) {
13796 mHandler.post(new Runnable() {
13797 @Override
13798 public void run() {
13799 try {
13800 callback.userStopped(userId);
13801 } catch (RemoteException e) {
13802 }
13803 }
13804 });
13805 }
13806 return ActivityManager.USER_OP_SUCCESS;
13807 }
13808
13809 if (callback != null) {
13810 uss.mStopCallbacks.add(callback);
13811 }
13812
13813 if (uss.mState != UserStartedState.STATE_STOPPING) {
13814 uss.mState = UserStartedState.STATE_STOPPING;
13815
13816 long ident = Binder.clearCallingIdentity();
13817 try {
13818 // Inform of user switch
13819 Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
13820 final IIntentReceiver resultReceiver = new IIntentReceiver.Stub() {
13821 @Override
13822 public void performReceive(Intent intent, int resultCode, String data,
13823 Bundle extras, boolean ordered, boolean sticky) {
13824 finishUserStop(uss);
13825 }
13826 };
13827 broadcastIntentLocked(null, null, intent,
13828 null, resultReceiver, 0, null, null, null,
13829 true, false, MY_PID, Process.SYSTEM_UID, userId);
13830 } finally {
13831 Binder.restoreCallingIdentity(ident);
Amith Yamasani13593602012-03-22 16:16:17 -070013832 }
13833 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013834 }
Amith Yamasani13593602012-03-22 16:16:17 -070013835
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013836 return ActivityManager.USER_OP_SUCCESS;
13837 }
13838
13839 void finishUserStop(UserStartedState uss) {
13840 final int userId = uss.mHandle.getIdentifier();
13841 boolean stopped;
13842 ArrayList<IStopUserCallback> callbacks;
13843 synchronized (this) {
13844 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks);
13845 if (uss.mState != UserStartedState.STATE_STOPPING
13846 || mStartedUsers.get(userId) != uss) {
13847 stopped = false;
13848 } else {
13849 stopped = true;
13850 // User can no longer run.
13851 mStartedUsers.remove(userId);
13852
13853 // Clean up all state and processes associated with the user.
13854 // Kill all the processes for the user.
13855 forceStopUserLocked(userId);
Amith Yamasani13593602012-03-22 16:16:17 -070013856 }
13857 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -070013858
13859 for (int i=0; i<callbacks.size(); i++) {
13860 try {
13861 if (stopped) callbacks.get(i).userStopped(userId);
13862 else callbacks.get(i).userStopAborted(userId);
13863 } catch (RemoteException e) {
13864 }
13865 }
13866 }
13867
13868 @Override
13869 public UserInfo getCurrentUser() {
13870 if (checkCallingPermission(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
13871 != PackageManager.PERMISSION_GRANTED) {
13872 String msg = "Permission Denial: getCurrentUser() from pid="
13873 + Binder.getCallingPid()
13874 + ", uid=" + Binder.getCallingUid()
13875 + " requires " + android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
13876 Slog.w(TAG, msg);
13877 throw new SecurityException(msg);
13878 }
13879 synchronized (this) {
13880 return getUserManager().getUserInfo(mCurrentUserId);
13881 }
Amith Yamasani13593602012-03-22 16:16:17 -070013882 }
13883
Amith Yamasani742a6712011-05-04 14:49:28 -070013884 private boolean userExists(int userId) {
Amith Yamasani258848d2012-08-10 17:06:33 -070013885 UserInfo user = getUserManager().getUserInfo(userId);
13886 return user != null;
13887 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013888
Amith Yamasani258848d2012-08-10 17:06:33 -070013889 UserManager getUserManager() {
13890 if (mUserManager == null) {
13891 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
13892 }
13893 return mUserManager;
Amith Yamasani742a6712011-05-04 14:49:28 -070013894 }
13895
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013896 private void checkValidCaller(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013897 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) return;
Amith Yamasani37ce3a82012-02-06 12:04:42 -080013898
13899 throw new SecurityException("Caller uid=" + uid
13900 + " is not privileged to communicate with user=" + userId);
13901 }
Amith Yamasani742a6712011-05-04 14:49:28 -070013902
13903 private int applyUserId(int uid, int userId) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013904 return UserHandle.getUid(userId, uid);
Amith Yamasani742a6712011-05-04 14:49:28 -070013905 }
13906
Dianne Hackborn599db5c2012-08-03 19:28:48 -070013907 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) {
Amith Yamasani2f6c9eb2012-02-06 15:31:35 -080013908 if (info == null) return null;
Amith Yamasani742a6712011-05-04 14:49:28 -070013909 ApplicationInfo newInfo = new ApplicationInfo(info);
13910 newInfo.uid = applyUserId(info.uid, userId);
Amith Yamasania4a54e22012-04-16 15:44:19 -070013911 newInfo.dataDir = USER_DATA_DIR + userId + "/"
13912 + info.packageName;
Amith Yamasani742a6712011-05-04 14:49:28 -070013913 return newInfo;
13914 }
13915
13916 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) {
Amith Yamasania4a54e22012-04-16 15:44:19 -070013917 if (aInfo == null
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070013918 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) {
Amith Yamasani742a6712011-05-04 14:49:28 -070013919 return aInfo;
13920 }
13921
13922 ActivityInfo info = new ActivityInfo(aInfo);
13923 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId);
13924 return info;
13925 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080013926}